Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 545
user1486691 Avatar asked Aug 28 '12 13:08

user1486691


2 Answers

IsInstanceOfType() checks whether the instance that you pass it is an instance of the type you called it on.

You're passing a System.Type instance to IsInstanceOfType(). That will only be true if you call it on typeof(Type) or one of its base classes.

like image 138
SLaks Avatar answered Sep 30 '22 14:09

SLaks


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
like image 35
Justin Avatar answered Sep 30 '22 13:09

Justin