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: c# casting
April 21st, 2010 at 3:02 am
Извините за то, что вмешиваюсь: Я разбираюсь в этом вопросе. Давайте обсудим….
в Китае а так же решают задачи ……
May 19th, 2010 at 7:29 pm
Это отличная идея. Готов Вас поддержать….
Руководитель группы снабжения
Mammal aMammal;
Walrus walrus = (Mammal) aMammal;
walrus.sharpenTusks();
That’ll work fine as long as aMammal really is a Walrus…..
July 2nd, 2010 at 12:34 pm
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….
August 30th, 2010 at 11:59 am
rhode http://oused9r8-tec.BEDROOMPROPERTY.INFO/tag/grandview+and+ri+rhode+bed/ : bed…
and…