I use the “is” operator to find a certain class:
for(int i=0; i<screens.Count; i++){
if(screen is ScreenBase){
//do something...
}
}
This works fine especially as it finds any class that inherits from the ScreenBase but not the base classes from ScreenBase.
I would like to do the same when I know only the Type and don’t want to instantiate the class:
Type screenType = GetType(line);
if (screenType is ScreenBase)
But this comparsion produces a warning as it will compare to the “Type” class.
The only alternative I know would be to compare with ==typeof but this would test only for the exact type and not the inherited ones.
Is there a way to get a similar behaviour like the “is” operator but for the type described by the Type-class?
If you want to know specifically if it derives from the type, use
Type.IsSubclassOf(). This will not work for interfaces.Otherwise if you want to know if the type could be assigned to a variable of a certain type, use
Type.IsAssignableFrom(). This will work for interfaces.Do note that you don’t necessarily need a type object to determine this, you can do this with an instance of the object using
Type.IsInstanceOfType(). It will behave more or less likeIsAssignableFrom().