views:

103

answers:

6

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

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

  • public virtual string ToString();
  • public virtual bool Equals(object objA, object objB);

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

+7  A: 

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

Thomas Levesque
You may want to take a look at http://stackoverflow.com/questions/1316518/how-did-microsoft-create-assemblies-that-have-circular-references where it is demonstrated that while circular dependencies are blocked by the IDE, they can be done using the command-line compiler (csc.exe).
Alfred Myers
I mean circular dependencies between assemblies...
Alfred Myers
A: 

I dont see the problem of a base-class returning a derived class.

Moreover I dont see circular dependencies since Object.ToString(); returns a String object. The String class derives from object, but so what? If both are in the same assembly, there is no problem.

Henri
It was more a chicken/egg situation, that's what confused me?
Dominic Zukiewicz
+2  A: 

A circular reference is only an issue across multiple projects, otherwise parent/child relationship wouldn't ever exist on both sides either.

Nick Craver
A: 
Drew Noakes
+2  A: 

Actually, it is not entirely true that all types inherit from Object. Please see Eric Lippert's blog entry on this.

Brian Rasmussen
A: 

In addition to what others have said you can also derive a class from a base class that uses the deriving class as a generic type parameter. There are a lot of neat uses for this pattern.

public class A<T>
{
}

public class B : A<B>
{
}
Brian Gideon