Here you will learn when to use struct over class in C#.
The Struct is a similar and lighter version of the class in C#. However, there are some pros and cons of Struct. After knowing this, you can understand 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 always 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 on assignment. 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 containingtypes and deallocated when the stack or the containing type gets deallocated. But, reference types are allocated 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, whereas 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 results in a negative impact on 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, that means when an instance of a reference type gets changed, it affects all the references indicating the instance. But, in the case of value types, it does not affect any of its copies. 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. Thus, before using Struct we should understand when to use Struct over Class in C#.