.netinheritanceclrparadox

How can System.Object use sub-classes as its return types?


It is true in .NET that all types inherit from System.Object.

What I find paradoxical, is a few methods on System.Object - namely

System.String is inherited from System.Object:

[Serializable]
public class String : Object { /*...*/ }

System.Boolean is inherited from System.Object:

[Serializable]
public struct Boolean : Object { /*....*/ }

What is the going on under the covers that allowed the System.Object class to allow sub-classes to be used as return types on its methods? How did this code ever compiled, as there seems to be a circular references. String <-> Object <-> Boolean.

I'm sure I will see statements, on "thats how it is implemented", but I can understand if these return types were "System.Object"'s themselves, and then a sub-class used the implemenations of string, bool and other System.ValueTypes to declare a new base class.

I hope that makes sense.

Thanks in advance,

Dominic


Solution

  • It's no big deal, a base class can always reference subclasses. For instance, this code is perfectly legal :

    class A
    {
        public B CreateB();
        {
            return new B();
        }
    }
    
    class B : A
    {
    }
    

    Note that it would be an issue if A and B were defined in separate assemblies, because that would require a circular assembly reference, which is not allowed