Why each class in .Net derives from System.Object? what are the benefits?
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:
Equals
helps test for equalityGetHashCode
helps with performance in collectionsGetType
- all objects have some typeFinalize
to support CLR finalizationBecause 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.
If 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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With