What is the difference between typeof and GetType()?

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

Comments

Popular posts from this blog

How do I calculate a MD5 hash from a string?

What is WSDL?