Search This Blog

Monday, November 25, 2013

Struct in C# Example

C# > Types > Struct

A struct type is a value type and is typically used for representing lightweight objects (color, zip, point).
  • cannot inherit from another struct or class
  • can be instantiated without using a new operator.
  • can implement an interface
  • can contain fields, constructors, methods, operators and events, but
  • if many members are required  you should make your type a class instead
Note:  Struct might be more efficient than a class in some scenarios. Using array of thousand of objects will be allocate more memory for referencing each object, so in this case, a struct would is more efficient and less expensive.






Example

        public struct strColor
        {
            public int r, g, b;
            public strColor(int p1, int p2, int p3)
            {
                r = p1;
                g = p2;
                b = p3;
            }
        }
       // Initialize using default and parameterized constructor
       strColor color1 = new strColor();
       strColor color2 = new strColor(10, 20, 30);
      // Declare object. It creates object without using the new  operator
       strColor color;
      //Initialize
       color.r = 10;
       color.g = 20;
       color.b = 30;