How to find an object from a class but not a superclass?

In C #, how can you find if an object is an instance of a particular class but not its class?

"is" will return true, even if the object is actually from a superclass.

+4
source share
5 answers
typeof(SpecifiedClass) == obj.GetType() 
+14
source

You can compare the type of your object with the type of class you are looking for:

 class A { } class B : A { } A a = new A(); if(a.GetType() == typeof(A)) // returns true { } A b = new B(); if(b.GetType() == typeof(A)) // returns false { } 
+3
source

Unfortunately, this is not possible in C # since C # does not support multiple inheritance. Give this inheritance tree:

 GrandParent Parent Child 

Child will always be an instance of each type above it in the inheritance chain.

+2
source

You can see several methods in the Type class: Type.IsInstaceOf as well as Type.IsSubclassOf

You can go to the class you are looking for and get the necessary information.

+1
source
 if(Obj.GetType() == typeof(ClassName)) 

It worked for me

0
source

All Articles