Abusing “as” operator

Casting to types using keyword as is one powerful features of C#. It allows exceptionless casting of reference types. If cast is not possible then null is returned. Although this is powerful language feature it opens also door to some questionable uses.

Instead of

public void DoSomething(SPField field)
{
   
var lookup = (SPFieldLookup
)field;

   
// Do something with field
}

you can write

public void DoSomething(SPField field)
{
   
var lookup = field as SPFieldLookup
;

   
// Do something with field
}

If field cannot be casted to SPFieldLookup then null is returned.

I saw some time ago how to abuse as keyword. Look at the following code line:

(field as SPFieldLookup).Title = "My field title";

Well, I think that we can call this line Mr. NullReferenceException. I have seen this kind of mistakes in code couple of times and almost 90% of cases this kind of code has caused troubles.

This example illustrates well why you should use Resharper from JetBrains. The next image shows you how Resharper warns you about possible NullReferenceException.

Possible null reference exception in cast

Liked this post? Empower your friends by sharing it!

Gunnar Peipman

Gunnar Peipman is ASP.NET, Azure and SharePoint fan, Estonian Microsoft user group leader, blogger, conference speaker, teacher, and tech maniac. Since 2008 he is Microsoft MVP specialized on ASP.NET.

    3 thoughts on “Abusing “as” operator

    • March 9, 2009 at 7:02 am
      Permalink

      In the last example you gave, wouldn’t it throw an InvalidCastException before throwing the possible NullReferenceException?

      How is one better than the other?

    • March 9, 2009 at 2:13 pm
      Permalink

      @Joe

      You took the words out of my mouth :)

    • March 9, 2009 at 2:27 pm
      Permalink

      Sorry, I forgot this (SPFieldLookup) line there. Look at this picture so it isn’t there. :P

    Leave a Reply

    Your email address will not be published. Required fields are marked *