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?


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 b3 = x.GetType() == typeof(Tiger); // true
bool b4 = x.GetType() == typeof(Animal); // false! even though x is an animal

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

bool b5 = typeof(Tiger).IsAssignableFrom(x.GetType()); // true
bool b6 = typeof(Animal).IsAssignableFrom(x.GetType()); // true! A variable of type Animal may be assigned a Tiger.

Need Your Help

Multiple keys with WPF KeyDown event

c# wpf keyboard keyboard-events keydown

I'm working with WPF KeyDown event (KeyEventArgs from Windows.Input). I need to recognize when user pressed F1 alone and Ctrl+F1.

GROUP BY statement HiveQL

hadoop hive hiveql

I'm a noobie to Hive. My question is why we need to use collect_set(col) while performing GROUP BY?