What is the difference between myCustomer.GetType() and typeof(Customer) in C#?
The result of both are exactly the same in your case. It will be your custom type that derives from System.Type
. The only real difference here is that when you want to obtain the type from an instance of your class, you use GetType
. If you don't have an instance, but you know the type name (and just need the actual System.Type
to inspect or compare to), you would use typeof
.
Important difference
EDIT: Let me add that the call to GetType
gets resolved at runtime, while typeof
is resolved at compile time.
GetType() is used to find the actual type of a object reference at run-time. This can be different from the type of the variable that references the object, because of inheritance. typeof() creates a Type literal that is of the exact type specified and is determined at compile-time.
Yes, there is a difference if you have an inherited type from Customer.
class VipCustomer : Customer
{
.....
}
static void Main()
{
Customer c = new VipCustomer();
c.GetType(); // returns typeof(VipCustomer)
}
For the first, you need an actual instance (ie myCustomer), for the second you don't
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)