When to use Struct over Class in C# (part 2)
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#.
🔸 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#.
🔸 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.