Search code examples
c#typesisinstance

When is obj.GetType().IsInstanceOfType(typeof(MyClass)) true?


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.


Solution

  • Each of those 3 lines will return true only if the object involved (derivedClass, baseClass and myClass respectively) is an instance of object, or of the undocumented RuntimeType object (note that Type is abstract), so for example the following would result in true statements:

    var myObject = new object();
    myObject.GetType().IsInstanceOfType(typeof(Console));
    
    myObject = typeof(Object);
    myObject.GetType().IsInstanceOfType(typeof(Console));
    

    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 myForm is a class that derives from Form, otherwise it will return false.

    typeof(Form).IsInstanceOfType(myForm);
    

    In your case myForm is in fact typeof(BaseClass), which is of the undocumented type RuntimeType (which derives from Type), and so you are only going to get true returned 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

    derivedClass is BaseClass
    baseClass is DerivedClass
    myClass is MyClass