• is operator - shows if object x is of type y. If this condition is true, then you can cast the instance to the given type. This accounts for inheritance. For example, all types (such as System.Int32) inherit from System.Object.  And 'is' Check if we can cast  that type  safety to  this type. Also We can use the '' as ''
  • keyword when we want to see if we can cast form one type to another,if  the cast is not valid then the ''as'' operator will return null.


  • GetType() method - a method on System.Object (and therefore available to all types) that returns the Type of the object. The Type class has a "FullName" property which returns a string of the name. Notice that you can tell the name of immediate type here, but it doesn't inheritance. For example, for an object on type "System.Int32"  the "is" keyword accounts for the current type (int) and the base type (object). GetType requires an instance and returns a type.

  • typeof keyword - Takes a Class an returns a Type (almost the inverse of typeof).

    "instance.GetType()==typeof(Class) " is not always equal  "instance is Class".there will one  problem when we use inheritance.


        BasePage inherits form Page,and BasePage inherits also from object,so if we

        test for(new BasePage()).GetType()==typeof(object) it'll return false because

         the types are different,but when we test using the is operator it's true.

         ((new BasePage()) is object) is true because (new BasePage()) is an object of   type BasePage, and also a Page and an object. The types might be different , but is operator checks whethere we can cast safely to this type.


    Notice :

    this same pattern can be applied to both value types (like a System.Int32) and reference types (like an XmlDocument):


    typeof() is an operator and GetType() is a method defined in System.Object an both of them returns and object of System.Type.


    System.Type.GetType is more than 7 times slower (on my dual core machine) than typeof.

    There are times when GetType is useful, but if the Type is well known to you then use typeof.


    Type aType = typeof(DateTime);

    instead of:



    By using the is operator, GetType method, and typeof keyword, we can effectively manage type information and solve several problems in various ways.

    Posted on 2008-11-14 17:41  {:)  阅读(383)  评论(0编辑  收藏  举报