Difference between Class and Struct in C#
Struct in C#:
In C#, struct is like a class that is used to store the data. However, unlike classes, a struct is a value type. We can easily use the struct keyword to define a struct.
Example:
[csharp]struct Employee {
public int id;
}
[/csharp]
Class in C#:
In C#, a class is a reference type that stores a reference to an object containing the data on the heap. It mainly used to combine the methods and fields into a sole unit.
Class vs Struct in C#:
Class | Struct |
1. In Class, data type is reference type and it stored on the heap. | 1. In Struct, data type is value type and it stored on the stack. |
2. It supports inheritance | 2. It doesn't support inheritance. |
3. Default values of a class type is null. | 3. Default values is the value produced by 'zeroing out' the fields of the struct. |
4. It permits initialization of instance fields. | 4. It doesn't permit initialization of instance fields. |
5. It supports destructor. | 5. It doesn't supports destructor. |
6. It permit declaration of parameter-less constructors | 6. It doesn't permit declaration of parameter-less constructors |
7. Assignment copies the reference. | 7. Assignment copies the values. |