Best way to check if System.Type is a descendant of a given class
-
07-07-2019 - |
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?
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;