Search code examples
c#.netreflectionsystem.reflection

Substitute for 'is' with types of object known in runtime


I'm trying to check if some Typeis instance of another Type. Like in this simple method, the best option would be:

bool Example(Type instance, Type runtimeKnwownType) {
    return instance is runtimeKnwownType;
}

It is the best option because is works with interfaces, however it doesn't work with Type and not constant right operand. Another option is Type.IsSubclassOf(object) doesn't work with interfaces. So there is my question for substition of is in this scenario.


Solution

  • Following your comment, you want to check the assignation of two types. Can you try this:

    Type.IsAssignableFrom(Type c)

    "True if c and the current Type represent the same type, or if the current Type is in the inheritance hierarchy of c, or if the current Type is an interface that c implements, or if c is a generic type parameter and the current Type represents one of the constraints of c."