Both class and struct have nearly same functionality but there is big difference between both. In this article I will try to explain difference between Class and Struct with an example.
Struct may seem similar to class, but there are many differences that make it alike. One such known difference is that class is reference type whereas structs are value type. There are few more differences which make class and struct alike from each other.
Let see the difference between struct and class. Class is a reference type and struct is value type. It means that if you copy a class to another class, second class still reference first class's address. As a result if you change anything in second class, it will reflect in first class also. Now because struct is value type, repeating same step will create a refresh copy of struct A into struct B and changing struct B values will not reflect in struct A.
Class | Struct (Structure) |
---|---|
Class is reference type. | Struct is value type. |
Use class keyword to define a class Eg. class MyClass { } |
Use struct keyword to define a struct. Eg. struct MyStruct { } |
All type of constructors are allowed. | Cannot create default constructor explicitly in struct. It is automatically provided by compiler and intialise all the fields with default value. You can only create parameterized constructor for struct. Click MSDN for more detail. |
Can create desctructor of a class. | Defining desctructor is not allowed. |
Variable assignment creates reference of class. | Variable assignment creates copy of Struct. |
A variable of a class type contains a reference to the data. It means, changing value in second object will automatically reflect in first object. | A variable of a struct type directly contains the data of the struct. So updating value has no affect at all. |