I\'ve seen many people use the following code:
Type t = typeof(obj1);
if (t == typeof(int))
// Some code here
But I know you could also
Use typeof
when you want to get the type at compilation time. Use GetType
when you want to get the type at execution time. There are rarely any cases to use is
as it does a cast and, in most cases, you end up casting the variable anyway.
There is a fourth option that you haven't considered (especially if you are going to cast an object to the type you find as well); that is to use as
.
Foo foo = obj as Foo;
if (foo != null)
// your code here
This only uses one cast whereas this approach:
if (obj is Foo)
Foo foo = (Foo)obj;
requires two.
Update (Jan 2020):
Example:
if(obj is Foo newLocalFoo)
{
// For example, you can now reference 'newLocalFoo' in this local scope
Console.WriteLine(newLocalFoo);
}