var type1 = typeof (ClassA);
var type2 = typeof (ClassB);
is type2
derived from type1
?
bool isDerived = // code....
var type1 = typeof (ClassA);
var type2 = typeof (ClassB);
is type2
derived from type1
?
bool isDerived = // code....
var type1 = typeof(ClassA);
var type2 = typeof(ClassB);
bool isDerived = type2.IsSubClassOf(type1);
void Main()
{
var type1 = typeof (ClassA);
var type2 = typeof (ClassB);
bool b = type1.IsAssignableFrom(type2);
Console.WriteLine(b);
}
class ClassA {}
class ClassB : ClassA {}
true if c and the current Type represent the same type, or if the current Type is in the inheritance hierarchy of c, or if the current Type is an interface that c implements, or if c is a generic type parameter and the current Type represents one of the constraints of c, or if c represents a value type and the current Type represents Nullable (Nullable(Of c) in Visual Basic). false if none of these conditions are true, or if c is null.
You can check the Type.Basetype
(see here) to see, which types you inherit from.
So you could write something like:
bool isDerived = type2.BaseType == type1;
Thanks to Daniel for pointing out my error with typeof!
If your intent is to check that Type2
is a class that is derived from Type1
, the Type.IsSubclassOf
method may be suitable. It returns true:
if the Type represented by the c parameter and the current Type represent classes, and the class represented by the current Type derives from the class represented by c; otherwise, false. This method also returns false if c and the current Type represent the same class.
In your example, isDerived
could be expressed as:
isDerived = type2.IsSubclassOf(type1)