Alex Rivera | Logout

What is the difference between myCustomer.GetType() and typeof(Customer) in C#?

Asked 2008-09-26T13:50:01.310
75

I've seen both done in some code I'm maintaining, but don't know the difference. Is there one?

let me add that myCustomer is an instance of Customer

Edit
Report

2 Answers

5

typeof(foo) is converted into a constant during compiletime. foo.GetType() happens at runtime.

typeof(foo) also converts directly into a constant of its type (ie foo), so doing this would fail:

public class foo
{
}

public class bar : foo
{
}

bar myBar = new bar();

// Would fail, even though bar is a child of foo.
if (myBar.getType == typeof(foo))

// However this Would work
if (myBar is foo)
answered 2008-09-26T14:14:45.917
2

typeof is executed at compile time while GetType at runtime. That's what is so different about these two methods. That's why when you deal with type hierarchy, you can find out the exact type name of a type simply by running GetType.

public Type WhoAreYou(Base base)
{
   base.GetType();
}
answered 2008-09-26T20:47:09.500

Your Answer