Depends On What Your Definition of “Is” Is
Yesterday I discovered the “is” keyword in C#. Is it a common keyword? Perhaps, but it’s the first time that I have seen it, so I wanted to share my newfound keyword with the world. At first, I thought I could replace conditionals such as:
if(variable.GetType() == typeof(DomainObject))
with the is keyword instead:
if(variable is DomainObject)
However, the is keyword functions like the term “is a” works in the world of hierarchies: It will not only return true if the same types are given, but also if the the given type to check is a derived member of a parent class. Take a look at this example:
public class FooBase { }
public class Foo : FooBase { }
class Program
{
static void Main()
{
object foo = new Foo();
Console.WriteLine(string.Format("{0, 40}: {1, -5}", "foo is Foo",
foo is Foo));
Console.WriteLine(string.Format("{0, 40}: {1, -5}",
"foo.GetType() == typeof(Foo)",
foo.GetType() == typeof(Foo)));
Console.WriteLine(string.Format("{0, 40}: {1, -5}", "foo is FooBase",
foo is FooBase));
Console.WriteLine(string.Format("{0, 40}: {1, -5}",
"foo.GetType() == typeof(FooBase)",
foo.GetType() == typeof(FooBase)));
Console.WriteLine();
}
}
And here’s the output:
As you can see, the object foo, which is of type Foo, obviously returns true for the cases where the exact type is checked. The is keyword also returns true, however, when foo is checked against FooBase. Note how the GetType()/typeof conditional returns false in this instance, however. Thus, if you want to check against a precise type, you have to stick with using GetType() and typeof to get the job done. Otherwise, however, the is keyword provides a much cleaner syntax to use (and is quite easy to read to boot).
Note that I deliberately used the general object type for foo in the above example. I did that because if you use the is keyword on exact types, ReSharper will catch that that particular conditional will always be true (or false, if comparing two different compile-time defined types):
Note that such convenience is not offered through the runtime method of type comparison.
