{love to code?}

August 13, 2009

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

Filed under: C# — navaneethkn @ 9:04 AM
Tags:

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.

2 Comments »

  1. This site rocks!

    Comment by Bill Bartmann — September 3, 2009 @ 3:19 AM | Reply

  2. I’m so glad I found this site…Keep up the good work

    Comment by Bill Bartmann — September 7, 2009 @ 3:42 AM | Reply


RSS feed for comments on this post. TrackBack URI

Leave a comment

Blog at WordPress.com.