Welcome to MSDN Blogs Sign in | Join | Help

Donkblog

Adventures into the world of amateurgramming. I'll leave the programming to the professionals.
GetType() or 'is' keyword?

Sometimes you might run into a case where you want to know the type of an object you are dealing with.  When someone first faces this situation they find two ways to solve this problem.  They can use GetType() or they can use the 'is' keyword.  At first glance it seem like they do the same thing, but they don't.  GetType will only return the current type of the item you dealing with, more examples can be found at the GetType msdn documentation.  However, the 'is' keyword check against all of the types the object could successfully be cast against.  As a small side note, these method both run in the same time in most cases.

 

 

        static void Main(string[] args)
        {
            Foo foo = new Foo();
 
            if (foo.GetType() == typeof(Bar))
            {
                Console.WriteLine("This will not print");
            }

            if (foo is Bar)
            {
                Console.WriteLine("This will print");
            }

        }

        class Foo : Bar
        {

        }

        class Bar
        {

        }
Posted: Monday, March 17, 2008 7:33 AM by Brandon Turner

Comments

rkpatrick said:

A more complete "is" equivalent would be GetType().IsAssignableFrom(...), as it covers subclasses as well as interfaces much like "is" (I use that quite a bit in reflection-based code)

# March 17, 2008 12:33 PM

Farrukh said:

thanks it helped me understanding the difference between the two.

# May 13, 2009 2:12 PM
Leave a Comment

(required) 

(required) 

(optional)

(required) 

  
Enter Code Here: Required

Comment Notification

If you would like to receive an email when updates are made to this post, please register here

Subscribe to this post's comments using RSS

Page view tracker