Velvet Star Monitor

Standout celebrity highlights with iconic style.

general

Check if instance is of a type

Writer Sophia Terry

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()?

1

9 Answers

The different answers here have two different meanings.

If you want to check whether an instance is of an exact type then

if (c.GetType() == typeof(TForm))

is the way to go.

If you want to know whether c is an instance of TForm or a subclass then use is/as:

if (c is TForm)

or

TForm form = c as TForm;
if (form != null)

It's worth being clear in your mind about which of these behaviour you actually want.

3
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
}

Yes, the "is" keyword:

if (c is TForm)
{ ...
}

See details on MSDN: (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:

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:

5

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

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

Try the following

if (c is TForm) { ...
}

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.

Or

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

or simpler

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

Your Answer

Sign up or log in

Sign up using Google Sign up using Facebook Sign up using Email and Password

Post as a guest

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy