Works on my machine

December 2012 Entries

Overuse of “as” keyword

Recently I realized that I am overusing "as" keyword. It is probably because its syntax is more fluent for me than ordinary cast. I see this overuse even in Microsoft examples. Let the following code show you what I mean:

object x = "1.0";
Version v = x as Version;
Console.WriteLine(v.Major);

and just for reference reasons ordinary cast:

object x = "1.0";
Version v = (Version)x;
Console.WriteLine(v.Major);

When you run first snippet it will crash on third line throwing NullReferenceException.
Second snippet on the other hand will crash on second line throwing InvalidCastException.

Now tell me, which gives you more info ?

For me the real problem with first one is that it can misguide in more complex scenarios. Imagine a method that returns some reference type and the last action is cast. What would be your first thought when your consuming code throws NullReferenceException ? That was my scenario and frankly I lost too much time analyzing good code. If I had only got InvalidCastException in proper line …