Check if instance is of a type

Lennie picture Lennie · Aug 24, 2010 · Viewed 206.2k times · Source

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

Answer

Jon Skeet picture Jon Skeet · Aug 24, 2010

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.