C# Structs Tutorial For Beginners With Examples

A Struct is a value type and is maintained by .NET runtime on the Stack memory area. The Struct type is usually used for small groups of related variables.
It is suitable for representing light weight objects such as mathematical objects like Rectangle, Polygons etc. or objects like Color, Employee records etc.
To declare a struct type the struct keyword is used.

Defining C# Structs

Structs are also called as structures and are efficient in terms of performance.
In the below example we have created a new user-defined value type called as Rect. Like int, bool etc. we can now declare a variable of type Rect.
    using System;
    public struct Rect
    {
        public int x, y;

        public Rect(int p1, int p2)
        {
            x = p1;
            y = p2;
        }
    } 
        

Using a Struct Type

A variable of type struct can be created by using the new keyword. However, the new keyword is not mandatory.
In the below example a Struct called as Rect was defined and is consumed by the Main method in the class Program.
    public struct Rect
    {
        public int x, y;

        public Rect(int p1, int p2)
        {
            x = p1;
            y = p2;
        }
    } 

    class Program
    {
        static void Main(string[] args)
        {
            Rect structRect = new Rect(10, 20);

            Console.WriteLine("X-axis of rectangle is: " + structRect.x);
            Console.WriteLine("Y-axis of rectangle is: " + structRect.y);

            Console.ReadLine();
        }
    }
        
Output:
X-axis of rectangle is: 10
Y-axis of rectangle is: 20

Constructors in Struct

Like a Class, Structs can also have constructors. However, it is mandatory for these constructors to have parameters. Parameter less constructors are not permitted in C# Structs.
In order to use the constructor the new keyword has to be used while creating a variable of type Struct. If the new keyword is not used then the constructor will not be invoked. In this case it may be required to initialize the variables inside the Struct by some other means.
In the below example a Struct with a parameterless constructor has been created. However, this will throw error while compiling as parameterless constructor is not allowed in C#.
    //Will THROW error
    public struct Rect
    {
        public int x, y;

        public Rect()
        {
            x = 10;
            y = 20;
        }
    }

    class Program
    {
        static void Main(string[] args)
        {
            Rect structRect = new Rect();

            Console.WriteLine("X-axis of rectangle is: " + structRect.x);
            Console.WriteLine("Y-axis of rectangle is: " + structRect.y);

            Console.ReadLine();
        }
    }
        

Methods and Properties in Struct

Structs can have Methods and Properties to expose the internal members to the consuming programs.
In the below example the Struct Rect has properties DimensionX and DimensionY to update and retrieve the values of X and Y dimensions of the rectangle. Similarly, a methodIncreaseDimensions was created in the Struct Rect to update the X and Y dimensions of the Rectangle.
    public struct Rect
    {
        private int x, y;

        public Rect(int p1, int p2)
        {
            x = p1;
            y = p2;
        }

        //Property to return X
        public int DimensionX
        {
            get
            {
                return x;
            }

            set
            {
                x = value;
            }
        }

        //Property to return Y
        public int DimensionY
        {
            get
            {
                return y;
            }

            set
            {
                y = value;
            }
        }

        //Increase the dimensions with the values passed to this method.
        public void IncreaseDimensions(int p1, int p2)
        {
            x = x + p1;
            y = y + p2;
        }
    }

    class Program
    {
        static void Main(string[] args)
        {
            Rect structRect = new Rect(20, 30);

            Console.WriteLine("X-axis of rectangle is: " + structRect.DimensionX);
            Console.WriteLine("Y-axis of rectangle is: " + structRect.DimensionY);

            structRect.IncreaseDimensions(10, 10);

            Console.WriteLine("X-axis of rectangle after increasing dimensions is: " + structRect.DimensionX);
            Console.WriteLine("Y-axis of rectangle after increasing dimensions is: " + structRect.DimensionY);
          
            Console.ReadLine();
        }
    }
        
Output:
X-axis of rectangle is: 20
Y-axis of rectangle is: 30
X-axis of rectangle after increasing dimensions is: 30
Y-axis of rectangle after increasing dimensions is: 40

Implementing Interfaces in a Struct

Structs can implement Interfaces and thus can expose its members as per the interface.
In the below example the Interface IOrientation has a method Axis which accepts two parameters. This Interface was implemented by Struct Rect.
    public interface IOrientation
    {
        void Axis(int xAxis, int yAxis);
    }

    public struct Rect : IOrientation
    {
        private int x, y;
        public int xaxis, yaxis;

        public Rect(int p1, int p2)
        {
            x = p1;
            y = p2;
            xaxis = 0;
            yaxis = 0;
        }

        public void Axis(int xAxis, int yAxis)
        {
            xaxis = xAxis;
            yaxis = yAxis;
        }
    }

    class Program
    {
        static void Main(string[] args)
        {
            Rect structRect = new Rect(20, 30);

            structRect.Axis(30, 0);

            Console.WriteLine("X orientation is: " + structRect.xaxis);
            Console.WriteLine("Y orientation is: " + structRect.yaxis);

            Console.ReadLine();
        }
    }
        
Output:
X orientation is: 30
Y orientation is: 0

Inheritance in C# Structs

Structs do not support inheritance. They cannot inherit from other Structs and that is one of the reason why they are light weight. Hence, it is important that while designing an application proper care is taken on the usage of Structs.
The Struct class itself inherits from System.Valuetype class and the Valuetype class inherits from System.Object base class. That is how .NET Framework classes are organized. However, when it comes to a object of type Struct then the behaviour is different.

Struct Vs Class

There are some similarities and differences between Structs and Classes. These are listed below:
  • Structs are value types and are maintained in Stack memory area whereas Classes are reference types and are managed in Heap memory area.
  • Performance wise Structs are better than Classes as .NET runtime works directly with a Struct instance.
  • Structs do not support Inheritance hence has some downsides when code reuse and other object oriented features has to be implemented in an Application.
  • Structs are not suitable when the size of data to be stored is large.
  • Structs cannot have a parameterless constructor or in other words it cannot have a default constructor.
  • Like Classes, Structs can also have properties, methods, indexers, constants, fields, events and operator methods.
  • Structs supports implementation of Interfaces and Attributes.