When should you use struct and not class in C#? My conceptual model is that structs are used in times when the item is merely a collection of value types. A way to
.NET supports value types
and reference types
(in Java, you can define only reference types). Instances of reference types
get allocated in the managed heap and are garbage collected when there are no outstanding references to them. Instances of value types
, on the other hand, are allocated in the stack
, and hence allocated memory is reclaimed as soon as their scope ends. And of course, value types
get passed by value, and reference types
by reference. All C# primitive data types, except for System.String, are value types.
When to use struct over class,
In C#, structs
are value types
, classes are reference types
. You can create value types, in C#, using the enum
keyword and the struct
keyword. Using a value type
instead of a reference type
will result in fewer objects on the managed heap, which results in lesser load on the garbage collector (GC), less frequent GC cycles, and consequently better performance. However, value types
have their downsides too. Passing around a big struct
is definitely costlier than passing a reference, that's one obvious problem. The other problem is the overhead associated with boxing/unboxing
. In case you're wondering what boxing/unboxing
mean, follow these links for a good explanation on boxing
and unboxing
. Apart from performance, there are times when you simply need types to have value semantics, which would be very difficult (or ugly) to implement if reference types
are all you have. You should use value types
only, When you need copy semantics or need automatic initialization, normally in arrays
of these types.