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
        {

        }