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.
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;
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;
name = "Steve";
In .NET there are two locations in which a type can be stored in memory:
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.
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 b 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.
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.
These are the main difference between Struct and Class in C#:
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! 🌟