To check if a type is a subclass of another type in C#, it's easy:
typeof (SubClass).IsSubclassOf(typeof (BaseClass)); // returns true
However, this will fail:
typeof (BaseClass).IsSubclassOf(typeof (BaseClass)); // returns false
Is there any way to check whether a type is either a subclass OR of the base class itself, without using an OR
operator or using an extension method?
This question is related to
c#
reflection
types
subclass
You should try using Type.IsAssignableFrom instead.
I'm posting this answer with the hope of someone sharing with me if and why it would be a bad idea. In my application, I have a property of Type that I want to check to be sure it is typeof(A) or typeof(B), where B is any class derived from A. So my code:
public class A
{
}
public class B : A
{
}
public class MyClass
{
private Type _helperType;
public Type HelperType
{
get { return _helperType; }
set
{
var testInstance = (A)Activator.CreateInstance(value);
if (testInstance==null)
throw new InvalidCastException("HelperType must be derived from A");
_helperType = value;
}
}
}
I feel like I might be a bit naive here so any feedback would be welcome.
typeof(BaseClass).IsAssignableFrom(unknownType);
If you're trying to do it in a Xamarin Forms PCL project, the above solutions using IsAssignableFrom
gives an error:
Error: 'Type' does not contain a definition for 'IsAssignableFrom' and no extension method 'IsAssignableFrom' accepting a first argument of type 'Type' could be found (are you missing a using directive or an assembly reference?)
because IsAssignableFrom
asks for a TypeInfo
object.
You can use the GetTypeInfo()
method from System.Reflection
:
typeof(BaseClass).GetTypeInfo().IsAssignableFrom(typeof(unknownType).GetTypeInfo())
Source: Stackoverflow.com