While writing a usual code in day-to-day development, we often avoid the minute details (plus and minus) between the two categories of an entity in C#.
Recently read about the subtleties included in the two types and some of the compelling reasons to compare the two options before creating a new entity. Most often we adhere to creating a Reference type (Class) thinking it to be scalable, performant (What is GC for?).
Post reading "Effective C# Programming", thought to document the details and to pay more attention in order to create the right type for my needs.
Why Value type?
1) Are created on Stack, does not involve GC.
2) Value types are copied when returned from a method or property. There is no danger of exposing internal structure (internals of an object).
2) Value types are copied when returned from a method or property. There is no danger of exposing internal structure (internals of an object).
Why not a Value type, always?
1) Limited support for OOPs! Remember, no inheritance, no polymorphism works here. Consider all as if they were sealed.
2) If backed by interface, would cost boxing.
3) Can not define a parameter less contructor (just to mention a limitation).
4) Since, passed by value, the whole object gets copied. Thus, not suggested to have a big value type.
5) Best suited to be Immutable only. There would be complication if not immutable, any user code may try to modify it but since copies are passed, the behaviour will not be right.
2) If backed by interface, would cost boxing.
3) Can not define a parameter less contructor (just to mention a limitation).
4) Since, passed by value, the whole object gets copied. Thus, not suggested to have a big value type.
5) Best suited to be Immutable only. There would be complication if not immutable, any user code may try to modify it but since copies are passed, the behaviour will not be right.
Why not a Reference type, always?
1) It involves heap allocation, and that too not inline. Which means there would be separate allocations (even if I am storing those objects in an array) for each object, which would eventually cause heap fragmentation, more garbage, more indirection (in terms of dereferencing).
Suggested rule of thumb:
Suggested rule of thumb:
You create value type, if
1) Type is only for data storage,
2) Public interface defined entirely by properties.
3) This type will never have subclasses.
4) This type will never be treated polymorphically.
1) Type is only for data storage,
2) Public interface defined entirely by properties.
3) This type will never have subclasses.
4) This type will never be treated polymorphically.
As a side note (on comparison).
- Reference types default to null.
- Value types default to all 0s.
- Nullable is again a value type (struct) which allows storing null. It would be interesting to find out the implementation behind.
- Reference types default to null.
- Value types default to all 0s.
- Nullable
No comments:
Post a Comment