Reputation: 8444
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
Upvotes: 1
Views: 208
Reputation: 310832
If you want to see a circular dependency in the .NET framework, then look no further than System.dll
, System.Xml.dll
and System.Configuration.dll
:
How Microsoft created these assemblies is a mystery to me. Actually, I might post this as another question...
Upvotes: 0
Reputation: 48949
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>
{
}
Upvotes: 0
Reputation: 116401
Actually, it is not entirely true that all types inherit from Object. Please see Eric Lippert's blog entry on this.
Upvotes: 2
Reputation: 292405
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
Upvotes: 7
Reputation: 630379
A circular reference is only an issue across multiple projects, otherwise parent/child relationship wouldn't ever exist on both sides either.
Upvotes: 2
Reputation: 5113
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.
Upvotes: 0