When I was first learning how to program C#, I wanted to use structs in strategic places. It seemed to make sense—structs could somehow make my programs better and speed them up somehow.
Over time, I started to realize most of the places I used structs would have been better off (or just as well-off) with classes. Structs are a way to have a type that is stored inline, without a reference to the heap memory. In .NET things like int
, DateTime
, or KeyValuePair
are structs—these are all types that require minimal memory.
Unless you have a need to create a new numeric type, it is best to avoid structs. Here are some drawbacks of structs:
List
, more memory needs to be copied—this causes slowdowns.struct
is larger than a reference, a List
of structs may be larger in memory (and slower) than a List
of class references.The C# language is designed mostly around classes. Structs are more of a feature that is needed for the standard library—to create types like int
, DateTime
, or KeyValuePair
. If you have types similar to those, a struct
can help performance slightly, but even then a class may be superior. In general, classes are preferred.