I’m looking at this piece of code written by someone else, and I’m wondering when it would evaluate to true. Basically, it is saying someType is an instance of someOtherType. Does it even make sense? So far, I’ve tried:
derivedClass.GetType().IsInstanceOfType(typeof(BaseClass))
baseClass.GetType().IsInstanceOfType(typeof(DerivedClass))
myClass.GetType().IsInstanceOfType(typeof(MyClass))
And all of them evaluate to false.
Any help is appreciated.
Each of those 3 lines will return true only if the object involved (
derivedClass,baseClassandmyClassrespectively) is an instance ofobject, or of the undocumentedRuntimeTypeobject (note that Type is abstract), so for example the following would result in true statements:Note that the type used (in this case
Console) doesn’t matter and has no effect on the outcome of the statement.Why?
The documentation for IsInstanceOfType tells us that it will return true if the object passed in is an instance of current type, so for example the following statement will return true if
myFormis a class that derives fromForm, otherwise it will return false.In your case
myFormis in facttypeof(BaseClass), which is of the undocumented typeRuntimeType(which derives fromType), and so you are only going to gettruereturned if this undocumented type happens to derive from the provided type – this is unlikely to be the desired behaviour.What should I use instead?
What you are probably after is the is keword, which returs true if the provided object is an instance of the given type