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?
If you're trying to do it in a Xamarin Forms PCL project, the above solutions using
IsAssignableFrom
gives an error:because
IsAssignableFrom
asks for aTypeInfo
object. You can use theGetTypeInfo()
method fromSystem.Reflection
:typeof(BaseClass).GetTypeInfo().IsAssignableFrom(typeof(unknownType).GetTypeInfo())
Apparently, no.
Here's the options:
is
andas
Type.IsSubclassOf
As you've already found out, this will not work if the two types are the same, here's a sample LINQPad program that demonstrates:
Output:
Which indicates that
Derived
is a subclass ofBase
, but thatBase
is (obviously) not a subclass of itself.Type.IsAssignableFrom
Now, this will answer your particular question, but it will also give you false positives. As Eric Lippert has pointed out in the comments, while the method will indeed return
True
for the two above questions, it will also returnTrue
for these, which you probably don't want:Here you get the following output:
The last
True
there would indicate, if the method only answered the question asked, thatuint[]
inherits fromint[]
or that they're the same type, which clearly is not the case.So
IsAssignableFrom
is not entirely correct either.is
andas
The "problem" with
is
andas
in the context of your question is that they will require you to operate on the objects and write one of the types directly in code, and not work withType
objects.In other words, this won't compile:
nor will this:
nor will this:
Conclusion
While the above methods might fit your needs, the only correct answer to your question (as I see it) is that you will need an extra check:
which of course makes more sense in a method:
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:
I feel like I might be a bit naive here so any feedback would be welcome.
You should try using Type.IsAssignableFrom instead.