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


Leave a Reply

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