Question

Consider the following code:

public class A 
{
}  

public class B : A 
{
}  

public class C : B 
{
}  

class D  
{  
    public static bool IsDescendantOf(this System.Type thisType, System.Type thatType)  
    {  
        /// ??? 
    } 

    void Main()
    {
        A cValue = new C();
        C.GetType().IsDescendantOf(cValue.GetType());
    }
}

What is the best way to implement IsDescendantOf?

Was it helpful?

Solution

Type.IsSubclassOf() Determines whether the class represented by the current Type derives from the class represented by the specified Type.

OTHER TIPS

You are probably looking for Type.IsAssignableFrom.

I realise this doesn't directly answer your question, but you might consider using this instead of the method in your example:

public static bool IsDescendantOf<T>(this object o)
{
    if(o == null) throw new ArgumentNullException();
    return typeof(T).IsSubclassOf(o.GetType());
}

So you can use it like this:

C c = new C();
c.IsDescendantOf<A>();

Also, to answer your question about the difference between Type.IsSubclassOf and Type.IsAssignableFrom - IsAssignableFrom is weaker in the sense that if you have two objects a and b such that this is valid:

a = b;

Then typeof(A).IsAssignableFrom(b.GetType()) is true - so a could be a subclass of b, or an interface type.

In contrast, a.GetType().IsSubclassOf(typeof(B)) would only return true if a were a subclass of b. Given the name of your extension method, I'd say you should use IsSubclassOf instead of IsAssignable to;

I think you are looking for this Type.IsSubclassOf()

Edit:

I don't know your requirements but may be thats the best way:

bool isDescendant = cValue is C;
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top