[c#] Check if instance is of a type

Using this to check if c is an instance of TForm.

c.GetType().Name.CompareTo("TForm") == 0

Is there a more type safe way to do it besides using a string as a param to CompareTo()?

This question is related to c# .net

The answer is


if(c is TFrom)
{
   // Do Stuff
}

or if you plan on using c as a TForm, use the following example:

var tForm = c as TForm;
if(tForm != null)
{
   // c is of type TForm
}

The second example only needs to check to see if c is of type TForm once. Whereis if you check if see if c is of type TForm then cast it, the CLR undergoes an extra check. Here is a reference.

Edit: Stolen from Jon Skeet

If you want to make sure c is of TForm and not any class inheriting from TForm, then use

if(c.GetType() == typeof(TForm))
{
   // Do stuff cause c is of type TForm and nothing else
}

Or

c.getType() == typeOf(TForm)

bool isValid = c.GetType() == typeof(TForm) ? true : false;

or simpler

bool isValid = c.GetType() == typeof(TForm);

A little more compact than the other answers if you want to use c as a TForm:

if(c is TForm form){
    form.DoStuff();
}

As others have mentioned, the "is" keyword. However, if you're going to later cast it to that type, eg.

TForm t = (TForm)c;

Then you should use the "as" keyword.

e.g. TForm t = c as TForm.

Then you can check

if(t != null)
{
 // put TForm specific stuff here
}

Don't combine as with is because it's a duplicate check.


Also, somewhat in the same vein

Type.IsAssignableFrom(Type c)

"True if c and the current Type represent the same type, or if the current Type is in the inheritance hierarchy of c, or if the current Type is an interface that c implements, or if c is a generic type parameter and the current Type represents one of the constraints of c."

From here: http://msdn.microsoft.com/en-us/library/system.type.isassignablefrom.aspx


Yes, the "is" keyword:

if (c is TForm)
{
    ...
}

See details on MSDN: http://msdn.microsoft.com/en-us/library/scekt9xw(VS.80).aspx

Checks if an object is compatible with a given type. For example, it can be determined if an object is compatible with the string type like this:


Try the following

if (c is TForm) { 
 ...
}