Frage

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?

War es hilfreich?

Lösung

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.

Andere Tipps

It's possible because being a value type or reference type is not inherited. The same applies to Enum. The class itself is a reference type, but enums are value types.

A possibly easier example is that all value types derive from System.Object, which is a reference type too.

int i = 3;
int j = 3;
object io = i;
object jo = j;

At this point, io and jo are references that refer to a copy of the values of i and j. The values can be extracted again using a cast:

int i2 = (int)io;
int j2 = (int)jo;

Functionally, this works roughly as if the conversion to object creates a class ValueWrapper<T> { public T value; } object behind the scenes, and io is set to new ValueWrapper<int> { value = i }. The cast from io to int then reads ((ValueWrapper<int>)io).value.

This is not exactly what happens, but what does happen is similar enough that this hopefully clarifies sufficiently.

Eric Lippert says in The C# Programming Language 4th Edition:

This point is frequently confusing to novices. I am often asked, “But how is it possible that a value type derives from a reference type?” I think the confusion arises as a result of a misunderstanding of what “derives from” means. Derivation does not imply that the layout of the bits in memory of the base type is somewhere found in the layout of bits in the derived type. Rather, it simply implies that some mechanism exists whereby members of the base type may be accessed from the derived type.

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top