Difference between class and struct in C# .Net

1. Classes are reference types and structs are value types. Since classes are reference type, a class variable can be assigned null. But we cannot assign null to a struct variable, since structs are value type.
2. When you instantiate a class, it will be allocated on the heap. When you instantiate a struct, it gets created on the stack.
3. You will always be dealing with reference to an object (instance) of a class. But you will not be dealing with references to an instance of a struct (but dealing directly with them).
4. When passing a class to a method, it is passed by reference. When passing a struct to a method, it’s passed by value instead of as a reference.
5. You cannot have instance Field initializers in structs, but classes can have.
Example:
class MyClass
{
int iVar = 10; // no syntax error.
public void MyFun( )
{
// statements
}
}
struct MyStruct
{
int iVar = 10; // syntax error.
public void MyFun( )
{
// statements
}
}
6. Classes can have explicit parameterless constructors, but structs cannot have an explicit declaration of a parameter less constructor. A struct always has a built-in public default constructor. This means that a struct is always instantiable whereas a class might not be since all its constructors could be private.
7. A structs static constructor is not triggered by calling the structs default constructor. It is for a class.
8. Classes support inheritance. But there is no inheritance for structs (structs don’t support inheritance, polymorphism).
9. Since struct does not support inheritance, access modifier of a member of a struct cannot be protected or protected internal.


11. A class is permitted to declare a destructor, but a struct cannot have a destructor. A destructor is just an override of object.Finalize in disguise, and structs, being value types, are not subject to garbage collection.
12. Classes are used for complex and large set data. structs are simple to use.

No comments:

Post a Comment