How to check if a class inherits another class without instantiating it?
Solution 1
To check for assignability, you can use the Type.IsAssignableFrom
method:
typeof(SomeType).IsAssignableFrom(typeof(Derived))
This will work as you expect for type-equality, inheritance-relationships and interface-implementations but not when you are looking for 'assignability' across explicit / implicit conversion operators.
To check for strict inheritance, you can use Type.IsSubclassOf
:
typeof(Derived).IsSubclassOf(typeof(SomeType))
Solution 2
Try this
typeof(IFoo).IsAssignableFrom(typeof(BarClass));
This will tell you whether BarClass(Derived)
implements IFoo(SomeType)
or not
Related videos on Youtube
Comments
-
atoMerz about 4 years
Suppose I have a class that looks like this:
class Derived : // some inheritance stuff here { }
I want to check something like this in my code:
Derived is SomeType;
But looks like
is
operator need Derived to be variable of type Dervied, not Derived itself. I don't want to create an object of type Derived.
How can I make sure Derived inheritsSomeType
without instantiating it?P.S. If it helps, I want something like what
where
keyword does with generics.
EDIT:
Similar to this answer, but it's checking an object. I want to check the class itself. -
Alex Hope O'Connor almost 9 yearsJust as a note to anyone else wondering, this won't return true when checking against generic type/interface definitions, as far as I can tell you need to search the inheritance chain and check for generic type definitions yourself.
-
Douglas Gaskell over 8 yearsAlex, how would you go about searching the inheritance chain of a generic type to accomplish this?
-
Furkan Ekinci about 8 years@AlexHopeO'Connor's note is important and I think solution is there stackoverflow.com/questions/457676/…
-
Seafish about 7 yearsFor PCL
typeof(SomeType).GetTypeInfo().IsAssignableFrom(typeof(Derived).GetTypeInfo())
-
Joel over 3 yearsFor those a little confused about the order, such as myself:
typeof(InvalidOperationException).IsAssignableFrom(typeof(Exception)) = false
typeof(Exception).IsAssignableFrom(typeof(InvalidOperationException)) = true