IsType

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.

  • Share This Post:
  • Share on Twitter
  • Share on Facebook
  • Share on Technorati

Print | posted on Tuesday, March 17, 2009 6:34 PM

Comments on this post

# re: IsType

Requesting Gravatar...
This isn't necessary as there are methods to do this already. The two methods you want to see on Type are IsSubclassOf (for the inheritance-based relationships) and IsAssignableFrom (which will handle interfaces and such).
Left by Jason Olson on Mar 17, 2009 7:14 PM

# re: IsType

Requesting Gravatar...
Thanks, Jason! I will update my posts on this topic. I wondered why there wasn't a way to do this built into the Type class, but I just missed the method when looking through the intellisense list.

I'll leave the post up because it's still an example of a recursive extension method and the functionality and implementation is a little different than IsSubclassOf.
Left by Chris Eargle on Mar 18, 2009 10:00 AM

# re: IsType

Requesting Gravatar...
That was inspiring,

do you mind puting the source code in your website so that I can see what have you done finally

Anyway, thanks for the post
Left by web development company on Aug 13, 2009 2:50 AM

Your comment:

 (will show your gravatar)