Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

People also ask

How can you tell if an object is inherited from a specific class?

You can compare two objects to determine the relationship, if any, between the classes from which they are created. The IsInstanceOfType method of the System. Type class returns True if the specified class inherits from the current class, or if the current type is an interface supported by the specified class.

Can a class inherit from another class?

In the Java language, classes can be derived from other classes, thereby inheriting fields and methods from those classes. Definitions: A class that is derived from another class is called a subclass (also a derived class, extended class, or child class).

What is gained by a class that inherits from another?

When you define a class to derive from another class, the derived class implicitly gains all the members of the base class, except for its constructors and finalizers. The derived class reuses the code in the base class without having to reimplement it. You can add more members in the derived class.

Is inherited C#?

In C#, inheritance allows us to create a new class from an existing class. It is a key feature of Object-Oriented Programming (OOP). The derived class inherits the fields and methods of the base class. This helps with the code reusability in 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))

Try this

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

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