Bookmark and Share

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.

blog comments powered by Disqus

KodefuGuru.GetInfo()

Chris Eargle
LinkedIn Twitter Technorati Facebook

Chris Eargle
Telerik Developer Evangelist, C# MVP

JustCode

Telerik .NET Ninja

 

INETA Community Speakers Program

 

MVP - Visual C#

 

Friend of RedGate

World Map

Tag cloud

Month List

Disclaimer

The opinions expressed herein are my own personal opinions and do not represent my employer's view in any way.

© Copyright 2010
Disclaimer: The opinions expressed herein are my own personal opinions and do not represent my employer’s view in any way.