Geeks With Blogs
Works on my machine

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;

and just for reference reasons ordinary cast:

object x = "1.0";
Version v = (Version)x;

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 …

Posted on Saturday, December 22, 2012 4:34 PM C# | Back to top

Comments on this post: Overuse of “as” keyword

# re: Overuse of “as” keyword
Requesting Gravatar...
I would say if you are using 'as' but not always following it up with a test for null, what's the actual benefit over the cast? (none that I know of)
Left by Gill Bates on Dec 26, 2013 12:21 AM

# re: Overuse of “as” keyword
Requesting Gravatar...
I found "as" to be more convenient to write than cast and I wanted to warn of using it automatically everywhere just because it is more convenient. It was very tempting in cases when I was absolutely sure that I have a not null object and that it is of some specific type. But even if we are absolutely sure there is a possibility that some new code will be written in the future and the previous assumption won't be valid anymore.

I agree that there is no point of converting an object by "as" keyword and then accessing it without a test for null.
Left by nabuk on Dec 26, 2013 1:35 AM

Your comment:
 (will show your gravatar)

Copyright © Jakub Niemyjski | Powered by: