What is the difference between typeof(Foo) and myFoo.GetType()?

This question is taken from Scott Hanselman‘s What a .NET developer should know post. To understand the difference, let us write a simple program.

class Foo
{
    /* .... */
}

class Program
{
    static void Main(string[] args)
    {
        Console.WriteLine("typeof(Foo) = " + typeof(Foo).Name);
        Foo f = new Foo();
        Console.WriteLine("f.GetType() = " + f.GetType().Name);
    }
}

Here is the output.

command-prompt

Let us add a subclass for Foo and try again.

class Foo
{
}

class SubFoo : Foo
{
}

class Program
{
    static void Main(string[] args)
    {
        Console.WriteLine("typeof(Foo) = " + typeof(Foo).Name);
        Foo f = new SubFoo();
        Console.WriteLine("f.GetType() = " + f.GetType().Name);
    }
}

command-prompt1

In general, f.GetType() returns runtime type of the instance. typeof(Foo) gives the compile time type of Foo.

Advertisements

2 thoughts on “What is the difference between typeof(Foo) and myFoo.GetType()?

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s