Tuesday, September 20, 2011

Structs in C#


Struct is very similar to a class but strcut is value type and class is reference type, .Net supports the value type and reference type unlike Java, in Java you can define only reference type.  Strcuts may leads to good performance where it’s used properly.

Reference types instances allocating in the managed heap and are garbage collected when there are no further references. Value types are allocated in the stack and so allocated memory is reclaimed as soon as their scope ends.  Using a value type instead reference type may result in fewer objects on the managed heap, which results less load to garbage collector (GC) and better performance.

Since for a value type, a compiler by default doesn’t generate a default constructor, struct doesn’t have parameter less constructor. And no finalizer, no virtual members and it derives only from System.ValuType, This System.ValueType may again derives from System.Object .    But structs can implement interfaces, in C# all primitive data types are value type except System.String
However value types have their poor sides too, when passing around big struct costlier than a reference type.

An example of declaring constructors.
    struct Point
    {
       private int x;
       private int y;

        public Point(int x, int y)
        {
            this.x = x;
            this.y = y;
        }
    }

An example of calling struct constructors.
              Point point1 = new Point();
            Point point2 = new Point(1,3);

No comments:

Post a Comment

Mapping data flows in Azure Data Factory

  Overview: Data flows are one of the features inside the Azure Data Factory which allows data engineers to develop data transformation logi...