Tutorial :Find out if a object has a specific class as an ancestor



Question:

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?


Solution:1

if (form is MyCustomFormType) {      // form is an instance of MyCustomFormType!  }  


Solution:2

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  }  


Solution:3

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.


Solution:4

The is operator:

bool isOk = form is MyCustomForm;  


Solution:5

Use the is operator.

e.g.

if (form is MyCustomFormType) {     do whatever  }  


Solution:6

void MyCoolMethod (Form form) {    if (form is MyCustomFormType)      // do your cool stuff here  }  


Solution:7

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.


Note:If u also have question or solution just comment us below or mail us on toontricks1994@gmail.com
Previous
Next Post »