Introduction

Structs are light versions of classes. Structs are value types and can be used to create objects that behave like built-in types.

Structs share many features with classes but with the following limitations as compared to classes.

When to use struct or classes?

To answer this question, we should have a good understanding of the differences.

S.N Struct Classes
1 Structs are value types allocated either on the stack or inline in containing types. Classes are reference types, allocated on the heap and garbage-collected.
2 Allocations and de-allocations of value types are, in general, cheaper than allocations and de-allocations of reference types. Assignments of large reference types are cheaper than assignments of large value types.
3 In structs, each variable contains its own copy of the data (except in the case of the ref and out parameter variables), and an operation on one variable does not affect another variable. In classes, two variables can contain the reference of the same object, and any operation on one variable can affect another variable.

In this way, struct should be used only when you are sure that,

In all other cases, you should define your types as classes.

e.g., Struct

using System;

struct Location
{
    public int x, y;

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

class Program
{
    static void Main(string[] args)
    {
        Location a = new Location(20, 20);
        Location b = a;
        a.x = 100;

        // Print the value of b.x
        Console.WriteLine(b.x);

        // Output: 20
    }
}

The output will be 20. The value of "b" is a copy of "a", so "b" is unaffected by change of "a.x". But in class, the output will be 100 because "a" and "b" will reference the same object.

I believe this blog has clarified most of the doubts about struct. If you find further queries about struct, please share with me so that everyone can have a clear understanding of this topic.