Logo 
Search:

C# FAQ

Submit Interview FAQ
Home » Interview FAQ » C#RSS Feeds

What is the difference between typeof and GetType()?

  Shared By: Estella Mitchell    Date: Nov 25    Category: C#    Views: 2259

Answer:

Apart from the obvious (i.e. typeof operates on a type whereas GetType operates on an object), the main thing to watch out for is that GetType returns the underlying type of the object, which may not be the same as the type of the reference to the object. For example:

class Base { }
class Derived : Base { }

class Program
{
static void Main()
{
ShowType( new Derived() );
}

static void ShowType( Base b )
{
Console.WriteLine(typeof(Base));
Console.WriteLine(b.GetType());
}
}
gives the following output:

Base
Derived

Share: 
 

Didn't find what you were looking for? Find more on What is the difference between typeof and GetType()? Or get search suggestion and latest updates.


Your Comment
  • Comment should be atleast 30 Characters.
  • Please put code inside [Code] your code [/Code].


Tagged: