Abusing “as” operator
Casting to types using keyword as is one powerful features of C#. 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.
