Why each class in .Net derives from System.Object? what are the benefits?
views:
72answers:
4If everything derives from a single class, then you can have behaviours that are universal - such as "is", "as", ToString() and GetHashCode(). You can use these operators/methods on any variable.
You can also pass anything generically as an 'object', which is a much nicer way than using void pointers.
I pose the opposite question to you: why not? If not for some common ancestor, how would you have a reference to "some object of any type"? Sometimes that's needed. Really, though, the System.Object class does have some useful methods that are generally useful for any type:
Equalshelps test for equalityGetHashCodehelps with performance in collectionsGetType- all objects have some typeFinalizeto support CLR finalization
Because these things are common to all types, you can have code (even before generics) that operate intelligently on multiple types.
With that said, though, in C# 4.0, they've introduced dynamic which is really a class hierarchy of its own. It bypasses static type-checking altogether and does not necessarily derive from object. MSDN has a good article about it, and Chris Burrows' blog series is interesting as well.
Without this behaviour:
- It would be almost impossible to compare objects of different classes using the Equals() method.
- You would not to be able to store instances of your class in the standard (non-generic) collections.
- You would not be able to rely on implicit conversion to the String type.
Also, if i'm not mistaken, the entire memory management model of .NET revolves around the System.Object type.
In the managed world you sacrifice the use of pointers, but you have references. So while you can't have something like this:
SomeClass obj = new SomeClass();
void* pObj = &obj;
you can have this for reference types (and value types via boxing, but then that's not really the same thing) thanks to inheritance:
object pObj = obj;
Of course there are other benefits, but I've mainly seen using object as a replacement for void pointers.