blog
Ottorino Bruni  

Difference between Struct and Class in C#

A good understanding of the differences in the behaviour of a Class and a Struct is crucial in creating a good software and developing in csharp.

Struct

A Struct is a value type that is typically used to encapsulate small groups of related variables and it is suitable for representing lightweight objects.

public struct Point 
{ 
    public int x;
    public int y; 
}

Class

A class is a reference type that enables to create your own custom types by grouping together variables of other types, methods and events. It defines the data and behaviour of a type.

public class Person 
{ 
    public string name;
    public Person() 
    { 
        name = "Steve"; 
    }
}

In .NET there are two locations in which a type can be stored in memory:

  • Stack;
  • Heap;

Stack

Value types are stored in the stack.

In this example, we create a variable int a = 3, after a variable int b = 4. On the stack, each variable is stored in the order it was created. In the end, we create a variable int c = b with the same value of b. So they both have 4 as value. For value types, each variable stores its own data.

Heap

The value of a reference type is stored on the heap and the address to this value is stored on the stack.

In this example, we create a class Student with a field name. Then we create an instance of the class Student called a and we set the value name to Alex. In the stack we store variable a and its value Alex on the heap. In the Stack, we store a pointer to the data. After we create another instance of the class Student called and we set the value name to Steve. In the Stack, we store variable b and its value Steve on the heap. Then we create another object called c and we set to b, in the stack we store variable c but its address is the same of b. If we change c name to Robert we are also changing the value of b that now is Robert and not Steve.

Memory

The benefit of storing data on the stack is that it’s faster, smaller, and doesn’t need the attention of the garbage collector, required for the heap. Value types are on the stack most of the time and are freed when the current method ends.

Reference types are on the heap and managed by the garbage collector. When a value type is on the stack, it takes up less memory than it would on the heap.

Difference

These are the main difference between Struct and Class in C#:

Difference between Struct and Class in C#

Tips

Microsoft suggests using a Struct instead of a Class if :

Instances of the type are small and commonly short-lived.

and to avoid Struct if:

It will have to be boxed frequently.

It isn’t immutable.

It has not an instance size under 16 bytes.

It logically doesn’t represent a single value, similar to primitive types.

Thanks for reading! ????

Leave A Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.