Thursday 3 May 2018

What are all classes in C# derived from?

Purpose:
  • Really simple question and it really just a litmus test to filter out the really bad candidates.
  • It is a good idea not to just answer the question simply, but actually delve into more detail and offer a greater understanding.

Potential Answer:
All classes derive and implicitly extend System.Object. This is because as a object orientated language the C# specification specifies this as a requirement. Interestingly even value types that are structs implicitly derive from System.Object. It provides a number of methods that sub-classes can override including Equals, GetType, ToString, GetHashCode, Finalize etc.. 

By having a common base class, then you can have behaviors that are universal and allows you to pass anything generically around as 'object'.

As a side note with the introduction of dynamic in C# 4.0 this has changed a bit in that it really has a class hierarchy of its own bypassing static type checking and does not necessarily derive from System.Object. See this blog

No comments:

Post a Comment