.NET: Value type inheritance - technical limitations?

4.3k Views Asked by At

I'm wondering if there are any technical reasons for why .NET value types do not support inheritance (disregarding interface implementation)... I can't at first glance think of a reason why value types shouldn't allow single base class inheritance.

(I mean, arguably, inheritance for value types would be bad if you end up with a huge inheritance hierarchy, but I'm mostly wondering if there are any runtime limitations rather than practical limitations.)

Thanks.

3

There are 3 best solutions below

2
On BEST ANSWER

Consider the memory allocated for a value type. The CLR knows exactly how much space to allocate for a variable of a value type, because it knows what fields there will be. It can't possibly end up with a subtype value with more fields.

Now we could have value type inheritance which just truncated things:

ExtendedValueType evt = new ExtendedValueType(...);
BaseValueType bvt = evt;
// Now you couldn't cast back to ExtendedValueType, because we'd have lost
// information

Likewise there's nowhere for type information to live in the value itself, so any virtual methods overridden by the extended type wouldn't be called via bvt, because as far as everything is concerned, the value is then just a value of BaseValueType. In other words, a lot of "natural" inheritance features would be missing in a way which I think would cause a lot of confusion.

1
On

Suppose it could be done.

You would be able to re-use some implementation.
But the real benefits of inheritance are Substitution and Polymorphism. They require use-by-reference.

And that is why interface implementation is supported because it always involves Boxing. But that would not do for inheritance.

0
On

I believe the reason why value types do not support inheritance is due to how they are represented in memory. The size of and consequently the data represented by a value type is dependent on its constituent fields. That is, if your value type contains an int and a string, the total size on a 32 bit system would be 8, or 4 (size of int) + 4 (size of pointer). What this means is that value types are represented in memory are a block of bytes, without any more information.

Now contrast that with class types, they are all size of pointers, or 4 on 32 bit systems. Since instances of class types are pointers, they can then refer to the things you need for inheritance, like a VMT (virtual method table) and a reference to the parent classes information. This is something a value type can't do, and hence why value types don't support inheritance.