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.
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);
}
}
In general, f.GetType() returns runtime type of the instance. typeof(Foo) gives the compile time type of Foo.



This site rocks!
Comment by Bill Bartmann — September 3, 2009 @ 3:19 AM |
I’m so glad I found this site…Keep up the good work
Comment by Bill Bartmann — September 7, 2009 @ 3:42 AM |