How to check if a class inherits another class without instantiating it?

C#InheritanceTypes

C# Problem Overview


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 inherits SomeType 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.

C# Solutions


Solution 1 - C#

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 - C#

Try this

typeof(IFoo).IsAssignableFrom(typeof(BarClass));

This will tell you whether BarClass(Derived) implements IFoo(SomeType) or not

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionatoMerzView Question on Stackoverflow
Solution 1 - C#AniView Answer on Stackoverflow
Solution 2 - C#Haris HasanView Answer on Stackoverflow