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?
Apparently, no.
Here’s the options:
isandasType.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
Derivedis a subclass ofBase, but thatBaseis (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
Truefor the two above questions, it will also returnTruefor these, which you probably don’t want:Here you get the following output:
The last
Truethere 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
IsAssignableFromis not entirely correct either.isandasThe “problem” with
isandasin 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 withTypeobjects.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: