Search code examples
c#.nettypesvalue-typereference-type

How / Why possible a value type derives from a reference type?


In .NET, all value types inherit from the class named System.ValueType. System.ValueType is a class, so it is a reference type.

My question is how and why possible a value type derives from a reference type?


Solution

  • The following is the key paragraph in the documentation

    Although ValueType is the implicit base class for value types, you cannot create a class that inherits from ValueType directly. Instead, individual compilers provide a language keyword or construct (such as struct in C# and Structure…End Structure in Visual Basic) to support the creation of value types.

    The inheritance occurs when the compiler compiles the overriden virtual methods of System.Object. The System.ValueType class simply provides more appropriate overloads of ToString(), GetHashCode() etc. As the document states the compiler uses these overloads if the struct keyword is used (in C#). This tells the compiler use the System.ValueType methods instead of the System.Object methods.