A coworker approached me earlier with a scenario that involved using reflection to find all of the properties in a class that were derived from a specific type. I walked through using reflection to do this, but then I was unable to find a way to interrogate the inheritance chain to determine if the type derived from the type we cared about. You can use the "is" operator because the type is Type, not an instance of the type.
I ended up making an extension method to do the job. Of course, one could use it like a typical helper method.
public static class TypeExtensions
{
public static bool IsType(this Type thisType, Type type)
{
if (thisType == null)
{
return false;
}
else if (thisType == type)
{
return true;
}
else
{
return IsType(thisType.BaseType, type);
}
}
}
This construct is pretty simple. We first make sure that we haven't reached the end of the inheritance chain. If so, we need to return that it isn't of the type specified. If the types are the same, we have a match. Otherwise, we need to interrogate the base type. I decided it was acceptable that this checked the original type as well, because one could call property.PropertyType.BaseType.IsType(someType) if the requirement was to check strictly for derived types.
Update: Jason Olson pointed out that IsSubclassOf would provide the functionality necessary to fulfill my coworker's requirement.