Here you will learn when to use Struct over class in C#.
Limitations of Struct
- Class is a reference type, whereas Struct is a value type.
- A default constructor or destructor cannot be created in Struct.
- Structs inherit from System.ValueType, cannot be inherited from another Struct or Class and cannot be a base class.
- Struct types cannot be abstract and are permanently sealed implicitly.
- Struct members cannot be abstract, sealed, virtual, or protected.
- Structs copy the entire value on the assignment, whereas reference types copy the reference. So, large reference type assignments are cheaper than the value types.
- Instance field declarations in Struct cannot include variable initializers. But, static fields in Struct can include variable initializers.
- A null value can be assigned to a struct as it can be used as a nullable type.
- Structs are allocated either on the stack or inline in containing types and deallocated when the stack or the containing type gets deallocated. But, reference types are given on the heap and garbage collected. So, the allocation and deallocation of structs are cheaper than classes.
- Array elements of reference types are references to the instances of the reference types that exist on the heap. In contrast, array elements of value types are the real instances of the value type. So, allocation and deallocation of value type arrays are much cheaper than the reference type arrays.
- Value types get boxed and unboxed during the typecasting. An excessive amount of boxing and unboxing negatively impacts the heap, garbage collector, and the application’s performance.
- If all the member fields are value types.
- If instances of the type are small and short-lived or embedded to other instances.
- If it logically denotes a single value, same as primitive types like int, double, etc.
- If the size of the instance is below 16 bytes.
- If it will not be boxed and unboxed again and again.
- If it is immutable, when an instance of a reference type gets changed, it affects all the references indicating the instance. But, it does not affect any of its copies in the case of value types. For this reason, changes in value types may raise confusion in many users. So, it should be immutable.
Generally, the use of value types will affect fewer objects in the managed heap, less load on the garbage collector, and thus better performance. However, it has a drawback as well. Value types will become expensive in the case of a big Struct. Therefore, before using Struct, we should understand when to use Struct over Class in C#.