This is one of the most common interview questions and the key difference is that struct is value type and class is reference type.

Also, there is no inheritance for structs as there is for classes. A struct cannot inherit from another struct or class, and it cannot be the base of a class. Struct itself, however, inherit from the base class Object. A struct can implement interfaces, and it does that exactly as classes do.



The general recommendation is to use structs for objects less than 64KB and classes for objects above that.



If you look deeper into .NET by using Reflector you can compare how struct and class are being compiled into MSIL.



Let's say we declared one class ClassTest and one struct StructTest




public class ClassTest
{
public object Data;
}


and


public struct StructTest
{
public object Data;
}


Internally .NET would compile them into very similar code:




.class auto ansi nested public beforefieldinit ClassTest
extends [mscorlib]System.Object
{
.method public hidebysig specialname rtspecialname instance void .ctor() cil managed { }

.field public object Data // data field

}



and for struct


.class sequential ansi sealed nested public beforefieldinit StructTest
extends [mscorlib]System.ValueType
{
.field public object Data // data field

}



Looking on the difference you see that class is converted into MSIL .class which has default constructor and inherit directly from Object while struct get converted into .class which doesn't have a constructor and inherit from System.ValueType.


There are also .class declaration difference:



'sealed' - on the struct which prevent derivation from a struct.



'sequential' - means that the date is represented in memory in the same order as you declared it i.e. is you have multiple field inside your struct they will be placed in memory in the same order you declared it.



'auto' - in opposite to the 'sequential' keyword 'auto' means that the layout of the class in memory will be decided by the runtime not your declaration.









Answers and Comments