Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the difference of getting Type by using GetType() and typeof()? [duplicate]

Tags:

Which one is the preferred way to get the type?

like image 618
user496949 Avatar asked Dec 27 '10 10:12

user496949


People also ask

What is the difference between GetType and Typeof?

typeof keyword takes the Type itself as an argument and returns the underline Type of the argument whereas GetType() can only be invoked on the instance of the type.

What is return type of GetType ()?

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

What is the use of typeof ()?

The TypeOf function is an important tool when dealing with complex code. It allows a programmer to quickly check a variable's data type—or whether it's “undefined” or “null”—without going through the code line by line! Additionally, the TypeOf function can also check whether an operand is an object or not.

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.


1 Answers

You can only use typeof() when you know that type at compile time, and you're trying to obtain the corresponding Type object. (Although the type could be a generic type parameter, e.g. typeof(T) within a class with a type parameter T.) There don't need to be any instances of that type available to use typeof. The operand for typeof is always the name of a type or type parameter. It can't be a variable or anything like that.

Now compare that with object.GetType(). That will get the actual type of the object it's called on. This means:

  • You don't need to know the type at compile time (and usually you don't)
  • You do need there to be an instance of the type (as otherwise you have nothing to call GetType on)
  • The actual type doesn't need to be accessible to your code - for example, it could be an internal type in a different assembly

One odd point: GetType will give unexpected answers on nullable value types due to the way that boxing works. A call to GetType will always involve boxing any value type, including a nullable value type, and the boxed value of a nullable value type is either a null reference or a reference to an instance of a non-nullable value type.

like image 193
Jon Skeet Avatar answered Nov 18 '22 12:11

Jon Skeet