Search code examples
c#class-designvalue-typereference-type

In C#, use of value types vs. reference types


My questions are:

  • When should we use value types and when reference types?
  • What are the advantages and disadvantages of one over other?
  • What if one uses reference types everywhere? Is there any harm in it?

Please also discuss advantages and disadvantages of each one. I want to understand that as well.


Solution

  • There seems to be a lot of confusion over this, and Jon Skeet does a good job of clearing it up in his book "C# In Depth, 2nd Ed." (section 2.3).

    My personal approach, which may or may not be right, is to ONLY use structs/enumerations (value types) to represent lightweight, atomic data structures that I know I'll be using frequently in some kind of logical or mathematical operations - think Point, etc.

    That way I figure I can avoid the garbage collection performance penalty. However, Jon points out in that section of his book that there's no real guarantee, especially in new versions of the runtime, whether something will go on the stack at all.

    So my best answer is use things like structs sparingly and be very conscious about why you're using them if you do. Watch out for premature optimization. And read that section in Jon's book if you can get your hands on a copy, because he does a good job of clarifying this whole topic.

    Related: When to use struct?