How to check object type at runtime in C #?

    2 answers 2

    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) 
      • 3
        To be perfectly precise, then ((object)obj).GetType() , GetType() method GetType() 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-type obj . - VladD
      • Well, basically, you are right. Although this is unlikely, of course, that someone will make such a trick. - Modus