views:

271

answers:

4

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?

+9  A: 

You are probably looking for Type.IsAssignableFrom.

Aistina
Yeap, that works for me. Thanks!
sh0gged
+6  A: 

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

alex
Hmm... That should work well too. Now I'm curious what's the difference between Type.IsAssgnableFrom and Type.IsSubclassOf?
sh0gged
type1.IsAssignableFrom(type2) will work if type1 is an interface
Kathy Van Stone
Now I guess that Type.IsSubclassOf() is more like what i was looking for. :) Thank you.
sh0gged
... 'couse in my case System.Type can be only a Class.
sh0gged
+1  A: 

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;
gsharp
I think in case of System.Type that just doesn't work.
sh0gged
+3  A: 

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 b.GetType().IsAssignableFrom(typeof(a)) 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;

Lee
Good point. Thanks.
sh0gged