May 022013

Thought I will share some interesting differences between a .net class and a struct.

Class Struct
Allocated on the heap. Allocated on the stack. They are value types and don’t require heap allocation.
A variable of a class type stores a reference to a dynamically allocated object. A variable of a struct type directly stores the data of the struct.
Supports user-specified inheritance. Does not support user-specified inheritance and all struct types implicitly inherit from type object.
An array of, class Point instances of, size 100 implies 101 separate objects are instantiated. One for the array and one each for the 100 elements. An array, of struct Point instances, of size 100 implies only one object i.e. the array is instantiated and the struct Point instances are stored inline in the array.
Dynamic allocation done via ‘new’ call. Struct constructors are invoked with the new operator but that does not imply that memory is being allocated. Instead of dynamically allocating an object and returning a reference to it, a struct constructor simply returns the struct value itself (typically in a temporary location on the stack), and this value is then copied as necessary.
With classes, it is possible for two variables to reference the same object and thus possible for operations on one variable to affect the object referenced by the other variable. With structs, the variables each have their own copy of the data, and it is not possible for operations on one to affect the other. For example, the output produced by the following code fragment depends on whether Point is a class or a struct.
Classes are kind of faster as only their references are copied around. Structs are copied by value unless we specify ref, out parameters hence the copying overhead is there.


Structs are particularly useful for small data structures that have value semantics. Complex numbers, points in a coordinate system, or key-value pairs in a dictionary are all good examples of structs. The use of structs rather than classes for small data structures can make a large difference in the number of memory allocations an application performs.

These differences are picked up from the C# 4.0 language specification.