As vs. Is
Tuesday, September 9th, 2008I was recently asked what the advantage is to using the C# as keyword as opposed to doing the classic type-in-parentheses style. Here’s the main difference in functionality, in case you were curious:
Mammal aMammal;
Walrus walrus = (Mammal) aMammal;
walrus.sharpenTusks();
That’ll work fine as long as aMammal really is a Walrus. If it’s not, an exception will be thrown. So we have to guard it like this:
Mammal aMammal;
if (aMammal is Walrus) {
((Walrus) aMammal).sharpenTusks();
}
Fine, that works, but it’s not as clean as this:
Mammal aMammal;
Walrus walrus = aMammal as Walrus;
if (null != walrus) {
walrus.sharpenTusks();
}
If aMammal isn’t really a Walrus, the walrus variable will be null. Now there are a lot fewer parentheses floating around, and in my opinion it’s much cleaner. I wouldn’t recommend this if there are a lot of choices for the type, because you’d need n variables, one for each option. In that case, you’re probably better off using the is operator. But if you find yourself needing to use is a lot in the first place, you might consider your design a little. That’s a code smell that indicates you might want to introduce an abstract method into your base class.