Tuesday, 16 October 2012

What is the difference between GetType() and typeof?

Trivially, whereas GetType operates on an object, typeof operates on a type. But, notice that GetType returns the underlying type of the object which can be different from the type of the reference to the object.

For instance:

class BaseClass {}
 
class DerivedClass: BaseClass {}
 
class Example
{
   static void RevealType (BaseClass baseClass)
   {
      Console.WriteLine (typeof(BaseClass));
      Console.WriteLine (baseClass.GetType());
   }
 
   static void Main()
   {
      RevealType (new DerivedClass());
   }
}
gives the following output:


 Example output (program output)
BaseClass DerivedClass

No comments :