Difference between Structure and Class in C#

Classes and Structure both are the essential data structure that binds the logically related data (or behaviour) to a unit. Let us find out how they are different from each other.

Following are the major differences between Structure and Classes

Structure Class
Structures are value types. Classes are refrence types.
You cannot use Inheritance in Structures. Classes support Inheritance.
Structures cannot be null Classes can be null
Stored in Stack Stored in Heap
Destructor is not there in case of Structure. Destructor is there in Class.
Structure cannot be abstract. Classes can be abstract.
They are value type so memory overhead is not there. Classes are refrence type so memory overhead is there.
Structures cannot contain parameterless constructor
struct A{
public A(){…} // error – cannot contain explicit parameterless constructor
}
Classes can contain parameterless constructor
class A{
public A(){…} // works fine
}
Structures are meant for small amount of Data. Classes can hold large amount of data





Let us understand it better through example
Class and Structure

Output
Structure

Explaination – Class is a refrence type and Structure is Value Type
Lets talk about the class first. obj and obj2 are the two instances created of class Program. In the line of code obj2=obj. What exactly is happening, obj is reference type, it holds the reference of original variable. now when obj2 is assigned with obj means now obj2 is pointing to the same variable what obj was pointing. See the diagram below
Class
So any changes made with obj object will automatically be reflected by obj2 also.

Now in Structure case
Structure
When we say ‘p2 = p1’ it means now p2 also have 2 variables.They are not pointing to any original variable, Both p1 and p2 work on their variables without affecting each other. Hence they are value types. Thank You..

If you have any doubt, feel free to comment, Happy Coding 🙂