C# FAQ: What is the difference between GetType and typeof

Microsoft .NET Framework, ASP.NET, Visual C# (CSharp, C Sharp, C-Sharp) Developer Training, Visual Studio


Jump to: navigation, search
CSharp-Online.NET:FAQs
edit

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


Personal tools