Structure in C#:

We have learned class in the previous section. Class is a reference type. C# includes a value type entity, which is called Structure. A structure is a value type that can contain constructors, constants, fields, methods, properties, indexers, operators, events and nested types. A structure can be defined using the struct keyword.

Example: Structure

public struct Discounts
{
    public int Cloths { get; set; }
    public int HomeDecor { get; set; }
    public int Grocery { get; set; }
}

A struct can be initialized with or without the new keyword same as primitive variable or an object. You can then assign values to the members of the structure as shown below.

Example: Initialize a structure
            
Discounts saleDiscounts;

saleDiscounts.Cloths = 10;
saleDiscounts.HomeDecor = 5;
saleDiscounts.Grocery = 2;

A struct is a value type so it is faster than a class object. Use struct whenever you want to just store the data. Generally structs are good for game programming. However, it is easier to transfer a class object than a struct. So do not use struct when you are passing data across the wire or to other classes.

Example: structure

struct Point
{
    private int _x, _y;

    public int x, y;

    public static int X, Y;

    public int XPoint {
        get 
        {
              return _x;
        }

        set 
        {
            _x = value;
            PointChanged(_x);
        }
    }

    public int YPoint
    {
        get
        {
            return _y;
        }
        set
        {
            _y = value;
            PointChanged(_y);
        }
    }

    public event Action<int> PointChanged;

    public void PrintPoints()
    {
        Console.WriteLine(" x: {0}, y: {1}", _x, _y);
    }

    public static void StaticMethod()
    {
        Console.WriteLine("Inside Static method");
    }
}

The above structure consists of different types of properties and events for the demo purpose. It includes private fields _x, _y, public fields x and y, static fields X and Y, public properties XPoint and YPoint, and PointChanged event. It also includes static and non-static methods. Notice that we raise the PointChanged event whenever XPoint or YPoint changes.

In the following code, we initialize the above Point struct with the new keyword as we initialize the class and also handle the PointChanged event:

Example: structure

class Program
{
    static void StructEventHandler(int point)
    {
        Console.WriteLine("Point changed to {0}", point);
    }

    static void Main(string[] args)
    {
        Point.StaticMethod();

        Point p = new Point();
        
        p.PointChanged += StructEventHandler;
        p.XPoint = 123;
        
        p.PrintPoints();
    }
}

Output:
Inside Static Method
Point changed to 123
X: 123, y: 0

Please note that if you want to use properties, methods or events, you MUST initialize the struct with the new keyword. The following will give a compile time error:

Example: structure

Point pto;

pto.XPoint = 100; // compile time error

Characteristics of Structure:

  • Structure can include constructors, constants, fields, methods, properties, indexers, operators, events & nested types.
  • Structure cannot include default constructor or destructor.
  • Structure can implement interfaces.
  • A structure cannot inherit another structure or class.
  • Structure members cannot be specified as abstract, virtual, or protected.
  • Structures must be initialized with new keyword in order to use it's properties, methods or events.

Difference between struct and class:

  • Class is reference type whereas struct is value type
  • Struct cannot declare a default constructor or destructor. However, it can have parametrized constructors.
  • Struct can be instasntiated without the new keyword. However, you won't be able to use any of its methods, events or properties if you do so.
  • Struct cannot be used as a base or cannot derive another struct or class.

Points to Remember :

  1. Structure is a value type and defined using struct keyword.
  2. Structure can be initialized with or without new keyword.
  3. Structure must be initialized with new keyword to use its' properties, methods and events.

Further Reading:

  1. Eric Lippert's blog on struct
  2. Choosing between class and structure