Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c#

.net

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

like image 464
user18931 Avatar asked Sep 26 '08 13:09

user18931


People also ask

What is return type of GetType ()?

The gettype() function returns the type of a variable.

What is GetType?

GetType Method is used to find the type of the current instance. This method returns the instances of the Type class that are used for consideration. Syntax: public Type GetType (); Return Value: This method return the exact runtime type of the current instance.

How do I use GetType?

The GetType method is inherited by all types that derive from Object. This means that, in addition to using your own language's comparison keyword, you can use the GetType method to determine the type of a particular object, as the following example shows.

What is typeof in C#?

The C# typeof operator ( GetType operator in Visual Basic) is used to get a Type object representing String. From this Type object, the GetMethod method is used to get a MethodInfo representing the String. Substring overload that takes a starting location and a length.


2 Answers

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.

like image 164
Kilhoffer Avatar answered Sep 30 '22 03:09

Kilhoffer


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.

like image 29
Jeffrey L Whitledge Avatar answered Sep 30 '22 03:09

Jeffrey L Whitledge