| (1)The main difference between struct and class is struct is a value type and class is a reference type.
(2)We can use or declare a destructor in class but is not possible in struct.
(3)One other thing is Classes have explicit parameter less constructors but not in struct.
(4)Now go on memory allocation When we instantiate a class then memory will be allocated on the heap but in struct memory is on the stack.
(5)Classes uses inheritance features but no inheritance for structs is possible.
(6)We cannot inherit struct from another struct or class, and it cannot be the base of a class. Like classes, structures can implement interfaces.
(7)It is possible to assign null null variable to class bt we cannot assign null to a struct variable because structs are value type.
(8)A struct cannot have an instance field but class can.Below example will clear the doubt.Example:-
class A
{
int x = 10; //correct no error
...
}
struct
{
int x = 10; //incorrectSyntax Error
}
(9)Struct are implicitly derived from a class which is called System.ValueType. The purpose of this System.ValueType is to override the virtual methods defined by System.Object.
(10)Creating a struct instance cannot cause a garbage collection but a reference type instance can cause garbage collection.
(11)Events declared in a class have their += and -= access automatically locked via a lock to make them thread safe but in events declared in a struct do not have their += and -= access automatically locked.
(12)The struct default access type is public. A struct should typically be used for grouping data. The class default access type is private, and the default mode for inheritance is private. A class should be used for grouping data and methods that operate on that data.
(13)We use use struct when the purpose is to group data and use classes when we require data abstraction and, perhaps inheritance. | | |