How to check if variable is of type of a type thats stored within 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 type in this way?

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 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.

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

You need to see if the Type of your instance is equal to the Type of the class. To get the type of the instance you use the GetType() method:

 u.GetType().Equals(t);

or

 u.GetType.Equals(typeof(User));

should do it. Obviously you could use '==' to do your comparison if you prefer.


In order to check if an object is compatible with a given type variable, instead of writing

u is t

you should write

typeof(t).IsInstanceOfType(u)

Need Your Help

Selected element won't change in d3

javascript svg charts d3.js

This snippet is a slightly modified version of the example http://bl.ocks.org/4063550 of a Reingold-Tilford Tree. Everything is similar, except I have slightly changed the code where one appends the

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.