Difference between Struct and Class in C#.net

Category: C#.NetOOPS Comments: No comments

Difference between Struct and Class

  • Struct are Value type and are stored on stack, while Class are Reference type and are stored on heap.
  • Struct “do not support” inheritance, while class supports inheritance. However struct can implements interface.
  • Struct should be used when you want to use a small data structure, while Class is better choice for complex data structure.
  •  You cannot have instance Field initializers in structs.But classes can have
    example:
    class MyClass
    {
    int myVar =10; // no syntax error.
    public void MyFun( )
    {
    // statements
    }
    }
    struct MyStruct
    {
    int myVar = 10; // syntax error.
    public void MyFun( )
    {
    // statements
    }
    }
  • 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.
  • classes are used for complex and large set data. structs are simple to use.
  • We can assign null variable to class. But we cannot assign null to a struct variable, since structs are value type.
  • We can declare a destructor in class but can not in struct.

Leave a Reply

Your email address will not be published. Required fields are marked *

*

HTML tags are not allowed.