Difference Between class and structure

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 SClass
{
int aVar =10; // no syntax error.
public void aFun( )
{
// statements
}
}
struct SStruct
{
int aVar = 10; // syntax error.

public void aFun( )
{
// statements
}
}
6. Classes can have explicit parameterless constructors. But structs cannot have

7. Classes must be instantiated using the new operator. But structs can be

8. Classes support inheritance.But there is no inheritance for structs.

9. Since struct does not support inheritance, access modifier of a member of a struct cannot be
    protected or protected internal.

10. A class is permitted to declare a destructor.But a struct is not

11. Classes are used for complex and large set data. structs are simple to use

12. Structure couldn't be Null like a class

13. Structure couldn't have a destructor such as class

14. Structure can't be abstract, a class can.

15. You can't use sizeof with classes but you can with structures

16. A structure must have always the default parameter less constructor be defined as public but a class might have one, so you can't define a private parameter less constructor

struct Me
    {
        private Me() // compile-time error
        {

        }
    }
    
class
Me
         {
            private Me() // runs Ok{
         }

Ebook Download
View all
Learn
View all