Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why each class in .Net derives from System.Object? what are the benefits?

Tags:

c#

.net

Why each class in .Net derives from System.Object? what are the benefits?

like image 386
Ram Avatar asked Aug 23 '10 06:08

Ram


2 Answers

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 equality
  • GetHashCode helps with performance in collections
  • GetType - all objects have some type
  • Finalize to 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.

like image 99
Chris Schmich Avatar answered Nov 07 '22 21:11

Chris Schmich


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.

like image 30
Jason Williams Avatar answered Nov 07 '22 21:11

Jason Williams