Tuesday, December 5, 2006

Types: is operator, GetType method, and typeof keyword

[This was originally posted at http://timstall.dotnetdevelopersjournal.com/types_is_operator_gettype_method_and_typeof_keyword.htm]

A common .Net question if "how do I determine if object x is of type y? For example, you may only want to perform certain operations on certain objects. Sometimes this can be solved by having that object implement an interface. But, there are other times you'll just need this ability. .Net provides easy ways to do this. Consider the code snippet below (notice that this is actually an MSTest unit test, but it's very easy to demonstrate quick code snippets because you can directly step into the code.

We notice a couple things:

  • 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.
  • 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).

    [TestMethod]
    public void Type_Int32()
    {
      int i = 5;

      //Show 'is' operator
      Assert.IsTrue(i is int);
      Assert.IsTrue(i is object);
      Assert.IsFalse(i is double);

      //Show GetType and typeof
      Assert.IsTrue(i.GetType().FullName == "System.Int32");
      Assert.IsTrue(i.GetType() == typeof(System.Int32));

      //Declare Type instance
      Type t1 = null, t2 = null;
      t1 = i.GetType();
      t2 = typeof(System.Int32);

      Assert.IsTrue(t1 == t2);

    }

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

    [TestMethod]
    public void Type_XmlDocument()
    {
      XmlDocument x = new XmlDocument();

      //Show 'is' operator
      Assert.IsTrue(x is XmlDocument);
      Assert.IsTrue(x is XmlNode);
      Assert.IsTrue(x is object);
      Assert.IsFalse(x is double);

      //Show GetType and typeof
      Assert.IsTrue(x.GetType().FullName == "System.Xml.XmlDocument");
      Assert.IsTrue(x.GetType() == typeof(System.Xml.XmlDocument));

      //Declare Type instance
      Type t1 = null, t2 = null;
      t1 = x.GetType();
      t2 = typeof(System.Xml.XmlDocument);

      Assert.IsTrue(t1 == t2);

    }

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

No comments:

Post a Comment