Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check if variable's type matches Type stored in a variable

User u = new User(); Type t = typeof(User);  u is User -> returns true  u is t -> compilation error 

How do I test if some variable is of some type in this way?

like image 769
Karan Avatar asked May 02 '12 13:05

Karan


People also ask

How do you check if a variable is a specific type?

To check the type of a variable, you can use the type() function, which takes the variable as an input. Inside this function, you have to pass either the variable name or the value itself. And it will return the variable data type.

How do you check if a variable is a certain type in C#?

The GetType() method of array class in C# gets the Type of the current instance. To get the type. Type tp = value. GetType();

Which operator is used to get instance data inside type Definition?

The typeof operator obtains the System.Type instance for a type. The argument to the typeof operator must be the name of a type or a type parameter, as the following example shows: C# Copy. Run.


2 Answers

The other answers all contain significant omissions.

The is operator does not check if the runtime type of the operand is exactly the given type; rather, it checks to see if the runtime type is compatible with the given type:

class Animal {} class Tiger : Animal {} ... object x = new Tiger(); bool b1 = x is Tiger; // true bool b2 = x is Animal; // true also! Every tiger is an animal. 

But checking for type identity with reflection checks for identity, not for compatibility

bool b5 = x.GetType() == typeof(Tiger); // true bool b6 = x.GetType() == typeof(Animal); // false! even though x is an animal  or with the type variable bool b7 = t == typeof(Tiger); // true bool b8 = t == typeof(Animal); // false! even though x is an  

If that's not what you want, then you probably want IsAssignableFrom:

bool b9 = typeof(Tiger).IsAssignableFrom(x.GetType()); // true bool b10 = typeof(Animal).IsAssignableFrom(x.GetType()); // true! A variable of type Animal may be assigned a Tiger.  or with the type variable bool b11 = t.IsAssignableFrom(x.GetType()); // true bool b12 = t.IsAssignableFrom(x.GetType()); // true! A  
like image 76
Eric Lippert Avatar answered Sep 20 '22 11:09

Eric Lippert


GetType() exists on every single framework type, because it is defined on the base object type. So, regardless of the type itself, you can use it to return the underlying Type

So, all you need to do is:

u.GetType() == t 
like image 29
Dave Bish Avatar answered Sep 22 '22 11:09

Dave Bish