Cast abuse

Every so often when reading through some C# code I'll run across the as keyword. Now this is a very nifty feature of C#. Just like the familiar parenthetical cast, it returns the object cast to the new type if it succeeds. However, if it fails then it simply returns null instead of throwing an exception.

This is cool when you aren't sure if you can cast an object to the type you need, but don't want to force the runtime to test if this can be done twice by using is followed by a parenthetical cast.

It's markedly not cool when you are not testing if the object you got is null. I see a lot of people doing stuff like (o as Widget).DoStuff(). This is the worst thing you could do here. Why? Because if o cannot be cast to Widget then the result will be null, and a NullReferenceException will be thrown. This will misdirect you to start checking why o is null, when in fact it is not. Using the "old-fashioned" parenthetical cast is appropriate here: ((Widget) o).DoStuff(). If the cast fails you will get the expected InvalidCastException and know immediately what the problem is.

Can someone please explain to me why as is so frequently abused like this?

Comments