tags:

views:

64

answers:

7

In C#, how can I find if a given object has a specific ancestor?

For example, say I have the following class structure.

ContainerControl
 |
 +----> Form
          |
          +--> MyNormalForm
          |
          +--> MyCustomFormType
                  |
                  +---> MyCustomForm

If I have a method like this:

 void MyCoolMethod (Form form)

How do I find if form descends from MyCustomFormType or not?

+6  A: 
if (form is MyCustomFormType) {
    // form is an instance of MyCustomFormType!
}
jhominal
if you also need to use it inside the if block, then `var theForm = form as MyCustomFormType; if (theForm != null) {}` also works.
chakrit
I feel lame.... I knew that. It is going to be a loooooong day.....
Vaccano
A: 

The is operator:

bool isOk = form is MyCustomForm;
Mau
+3  A: 
if( form is MyCustomFormType)

If you are going to cast it to that type you should use the as operator and check for null.

MyCustomFormType myCustomFormType = form as MyCustomFormType;
if( myCustomFormType != null)
{
   // this is the type you are looking for
}
Shaun Bowe
You win IMO for the practical use case.
Andrew Anderson
A: 

Use the is operator.

e.g.

if (form is MyCustomFormType) {
   do whatever
}
Andrew Anderson
A: 
void MyCoolMethod (Form form) {
  if (form is MyCustomFormType)
    // do your cool stuff here
}
Tahbaza
A: 
var myCustomForm = form as MyCustomFormType;
if(myCustomForm != null)
{
    // form was a MyCustomFormType instance and you can work with myCustomForm 
}

Avoid is if you want to manipulate the form as a MyCustomFormType. By using as, you only need one cast.

Romain Verdier
+2  A: 

As any number of respondents have added: through the is (or as) operators.

However, wanting to find out the exact type is a classic code smell. Try not to do that. If you want to make decisions based on the exact type of form, try instead to put that logic in overridden virtual methods rather than outside your class.

Pontus Gagge
Good point. The method I am putting it in is actually an extension method (ShowDialog2). I need to show the dialog differently based on its ancestry. (Modal vs modeless)
Vaccano