Search code examples
c#.netruntimeinternalsvalue-type

.NET: Value type inheritance - technical limitations?


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.


Solution

  • 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.