Tag Archives: ValueType

CLR: System.ValueType

Every .NET developer knows that all types derive from the System.Object base class. But if you ask developers what the base class of a struct or enum is you will find many do not know or simply assume it is System.Object. To get the most from the CLR you should understand the type system you are using.

All value types derive either directly or indirectly from the System.ValueType class. There are only two ways to create a new value type and that is via a struct or an enum. An enumeration actually has an extra class between the value type and the generated enum called System.Enum. We can see the inheritance relationship in the following diagram.

System.ValueType Inheritence

System.ValueType
You might have rarely if ever noticed this class because it is special. You are not allowed to derive from it yourself and so only the compiler can create value types that derive from it directly, which is does for struct definitions. It overrides the implementation of the Equals,  GetHashCode and ToString in order to provide the semantics you would expect for a value type instead of those for a reference type.

System.Enum
The compiler uses this as the base class for all enum definitions. Although it looks as if you can define the base class by specifying something like public enum : short, this is merely syntactic sugar making it easy for you to define how the enumeration values are stored.

Reference Classes
All the blue boxes in the above diagram are reference classes. Yes, it is somewhat ironic that the value type is actually a reference type itself! This means that if you cast a value type instance to System.ValueType then your value will be boxed into a reference. Really it is no different to casting to System.Object. All enum types have the additional ability to be cast to System.Enum and likewise they will be boxed.

Value Types
The red boxes show the two ways of creating new value types.

Built-in Types
Orange boxes show how the well-known built-in types are implemented. They are all struct definitions that also implement various interfaces. You can see this for yourself by using Visual Studio and right-clicking an int keyword and selecting the Go To Definition.

System.Int32

The Nullable generic type is just a structure with a type parameter constraint to ensure it only works with value types.

System.Nullable

There are few uses for System.ValueType but one is using it as a parameter type. This allows the caller to pass any value type such as long, bool, decimal, double, nullable, struct or enum. But it prevents the passing of a reference type. Granted, there are not many times when you need to restrict the passed parameter to the full set of value types but when you need the ability you do have a solution. But do remember that the passed in value will have been boxed!

Additional Resources
MSDN – System.ValueType