BCA / B.Tech 9 min read

Structs in C# .NET

Structs in C# .NET in Hindi 


Structs (full name is structure) are value types in C#. Structs are used when we need small and lightweight data types that store the value directly in memory.

We use structs just like classes, but there are some key differences between them:

  • Structs are value types, whereas classes are reference types.
  • Structs are stored in stack memory, not heap memory.
  • Inheritance is not supported in structs (you cannot derive a struct from another struct).
  • Using Structs
How to Declare and Use Structs:

using System;

struct Point
{
    public int X;
    public int Y;

    public Point(int x, int y)
    {
        X = x;
        Y = y;
    }

    public void Display()
    {
        Console.WriteLine($"Point is at ({X}, {Y})");
    }
}

class Program
{
    static void Main()
    {
        Point p = new Point(10, 20); // Created an object of the struct
        p.Display(); // Output: Point is at (10, 20)
    }
}
In this example, we have created a struct named Point which has two variables (X and Y) and one method (Display). It can be used like an object.

Overloading Structs: Overloading means defining multiple constructors or methods in a struct, whose parameters are different.

struct Rectangle
{
    public int Length;
    public int Breadth;

    // Constructor Overloading
    public Rectangle(int side)
    {
        Length = Breadth = side; // A square is being formed
    }

    public Rectangle(int length, int breadth)
    {
        Length = length;
        Breadth = breadth;
    }

    public int Area()
    {
        return Length * Breadth;
    }
}

class Program
{
    static void Main()
    {
        Rectangle square = new Rectangle(5); // Overloaded constructor (Square)
        Console.WriteLine("Square Area: " + square.Area());

        Rectangle rect = new Rectangle(4, 6); // Overloaded constructor (Rectangle)
        Console.WriteLine("Rectangle Area: " + rect.Area());
    }
}
Here, two different constructors are given in the struct, with which you can create a square and a rectangle.

Calling Structs in .NET with C#: Calling structs is just like class objects, but the struct is stored directly on the stack. Below is an example:

struct Circle
{
    public double Radius;

    public Circle(double radius)
    {
        Radius = radius;
    }

    public double Area()
    {
        return Math.PI * Radius * Radius;
    }
}

class Program
{
    static void Main()
    {
        Circle c = new Circle(5); // Created a struct instance
        Console.WriteLine("Circle Area: " + c.Area());
    }
}


When to use Structs?

  • When the data is lightweight (e.g., coordinates, colors, etc.).
  • When the data is short-lived and can be stored in stack memory.
  • When inheritance is not needed.
  • Using structs correctly can lead to performance improvement because access on stack memory is faster.