Defining Value Types

One of the things that’s been floating around in my mind is the difference between object types and value types.  Conceptually, it’s the difference between a dialog and an integer or string.  In my mind, I understand the intent, but I dislike categorizing by intent, as that leads to fuzzy definitions that eventually become meaningless.

The other way to define value types is by storage - stack vs. heap.  I really don’t like this, though, as one of the advantages of value types is that it’s safe to pass them by reference.  I would say a string in C# is a value type, even though it’s a class (and therefore passed by reference).

So, here’s a set of criteria to determine if something is a value type or not.  These criteria don’t specify whether a particular type could be implemented as a value type, only whether or not they are a value type as implemented.

  1. The type must be immutable.  Any methods called on the type cannot change its members.  If a modification is desired, the method should create a new object of the same type, and return that object.
  2. The type must only reference other value types.

If your type follows these two rules, it is guaranteed to be side-effect free.

Rule #2 might be relaxed, if the reference type that the type holds is guaranteed to never be exposed (so nothing can ever modify it), and the object never modifies it itself.