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.
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.
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.
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.
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
{
}