In .NET languages, such as C#, classes are reference types and structures are value types. Reference types are allocated on the heap, and memory management is handled by the garbage collector. Value types are allocated on the stack or inline and are deallocated when they go out of scope. In general, value types are cheaper to allocate and deallocate. However, if they are used in scenarios that require a significant amount of boxing and unboxing, they perform poorly as compared to reference types.
Do not define a structure unless the type has all of the following characteristics:
-
It logically represents a single value, similar to primitive types (integer, double, and so on).
-
It has an instance size smaller than 16 bytes.
-
It is immutable.
-
It will not have to be boxed frequently.
If one or more of these conditions are not met, create a reference type instead of a structure. Failure to adhere to this guideline can negatively impact performance.