X

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.

Liked this post? Empower your friends by sharing it!
Categories: C#

View Comments (3)

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

    How is one better than the other?

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

Related Post