tags:

views:

196

answers:

4

In C# how can you find if an object is an instance of certain class but not any of that class’s superclasses?

“is” will return true even if the object is actually from a superclass.

A: 

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

GrandParent
  Parent
   Child

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

Andrew Hare
After looking at your answer for a few minutes, I think I know what you mean. I think.
Tundey
+5  A: 
typeof(SpecifiedClass) == obj.GetType()
chaowman
-1 This does not answer the question - it is not possible for one type to inherit from another without also inheriting from all other types in the inheritance chain.
Andrew Hare
This answer works, and funny enough, it works for all question versions (check history) - both for "superclass" and "subclass".
DK
+1  A: 

You may want to look at a couple of methods on the Type class: Type.IsInstaceOf and Type.IsSubclassOf

You can pass in the class you're looking for and get the information you need.

CubanX
That is when you want to compare two objects with each other. My case is to compare an object with a class.
Ali
It's true these are types, but you can get the Type class for an object with obj.GetType.Example:obj.GetType().IsSubclassOf(typeof(ClassYouAreLookingFor))orobj.GetType().IsInstanceOf(typeof(ClassYouAreLookingFor))Should accomplish what you're looking for.
CubanX
+1  A: 

You could compare the type of your object to the Type of the class that 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
{
}
Andy