IsSubclassOf

It appears that I missed an important method that belongs to Type when making the extension method IsType. Jason Olson pointed out that type.IsSubclassOf would provide the functionality necessary to fulfill my coworker's requirement. The functionality and implementation of IsType is a little different, however. IsType will check the current type then recursively checks each BaseType. IsSubclassOf will return false if the original check indicates that the types are identical. Also, it uses a while loop rather than recursively calling itself.

public virtual bool IsSubclassOf(Type c)
{
    
Type baseType = this;
    
if (baseType != c)
    {
        
while (baseType != null)
        {
            
if (baseType == c)
            {
                
return true;
            }
            baseType = baseType.BaseType;
        }
        
return false;
    }
    
return false;
}

I find this interesting. Leave a comment on whether you prefer recursive methods or loops.

I also discovered that the compiler modifies my code to the following:

public static bool IsType(this Type thisType, Type type)
{
    
if (thisType == null)
    {
        
return false;
    }
    
return ((thisType == type) || thisType.BaseType.IsType(type));
}

I prefer to keep the original style because I feel it is more readable. In addition to the if statement, I had the option to use the boolean trick or the ternary operator to perform the same function. I tend to think that if statements are easier to read, but I'm always looking to improve my coding style. Let me know what you prefer.

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

Print | posted on Wednesday, March 18, 2009 1:39 PM

Comments on this post

# re: IsSubclassOf

Requesting Gravatar...
Nice post,

This was exactly what I wished for

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

Your comment:

 (will show your gravatar)