1. Classes are reference types and structs are value types so a class variable can be assigned null but we cannot assign null to a struct variable.
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 initializers.
6. Classes can have explicit parameterless constructors. But structs cannot have explicit parameterless constructors.
7. Classes must be instantiated using the new operator. But structs can be instantiated without using the new operator.
8. Classes support inheritance.But there is no inheritance for structs. ( structs don't support inheritance polymorphism ) So we cannot have a base structure and a derived structure. But like classes, structures can implement interfaces.
9. Since struct does not support inheritance, access modifier of a member of a struct cannot be protected or protected internal.
10. It is not mandatory to initialize all Fields inside the constructor of a class.
But all the Fields of a struct must be fully initialized inside the constructor.
11. A class is permitted to declare a destructor.But a struct is not permitted to declare a destructor.
12. classes are used for complex and large set data. structs are simple to use. structs are useful whenever you need a type that will be used often and is mostly just a piece of data.
13. Creating a struct instance cannot cause a garbage collection (unless the constructor directly or indirectly creates a reference type instance) whereas creating a reference type instance can cause garbage collection.
14. 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.
15. A struct is implicitly sealed, a class isn't.
16. A struct can't be abstract, a class can.
17. A struct can't call : base() in its constructor whereas a class with no explicit base class can.
18. A struct can't declare abstract function members, an abstract class can.
19. A struct can't declare virtual function members, a class can.
20. A struct can't declare sealed function members, a class can.
21. A struct can't declare override function members, a class can. The one exception to this rule is that a struct can override the virtual methods of System.Object, viz, Equals(), and GetHashCode(), and ToString().
No comments:
Post a Comment