As vs. Is

I 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.

Tags:

4 Responses to “As vs. Is”

  1. Kylie Batt Says:

    Извините за то, что вмешиваюсь: Я разбираюсь в этом вопросе. Давайте обсудим….

    в Китае а так же решают задачи ……

  2. Kylie Batt Says:

    Это отличная идея. Готов Вас поддержать….

    Руководитель группы снабжения
    Mammal aMammal;
    Walrus walrus = (Mammal) aMammal;
    walrus.sharpenTusks();

    That’ll work fine as long as aMammal really is a Walrus…..

  3. JON Says:


    PillSpot.org. Canadian Health&Care.No prescription online pharmacy.Special Internet Prices.Best quality drugs. High quality pills. Buy drugs online

    Buy:100% Pure Okinawan Coral Calcium.Valtrex.Zovirax.Prednisolone.Actos.Synthroid.Accutane.Mega Hoodia.Zyban.Human Growth Hormone.Arimidex.Prevacid.Nexium.Retin-A.Lumigan.Petcam (Metacam) Oral Suspension….

  4. and Says:

    rhode http://oused9r8-tec.BEDROOMPROPERTY.INFO/tag/grandview+and+ri+rhode+bed/ : bed…

    and…

Leave a Reply

Celtic cross