2 answers
The C # is
operator checks whether an object is an instance of a type or a type derived from it.
if (obj is MyObject) { }
MSDN Help: is operator .
|
Only is
will return true
if obj
is a subclass of MyObject
, sometimes this is undesirable. For an accurate type comparison, write this:
obj.GetType() == typeof(MyObject)
- 3To be perfectly precise, then
((object)obj).GetType()
,GetType()
methodGetType()
may be overloaded and return any nonsense. - VladD - The GetType method, firstly, is not virtual, and secondly, polymorphism cannot be reduced to a basic type. - Modus
- This is yes, but it can be blocked with
new
. ideone.com/rG79xt . We don’t know the compile-time-typeobj
. - VladD - Well, basically, you are right. Although this is unlikely, of course, that someone will make such a trick. - Modus
|