Benefits of using “as” in C#

The “as” keyword is very useful in managed code because it solves a very common problem.

Suppose you have this:

object o;

string s = (string)o;

but what if o is null? Then you will get a NullReferenceException. Sometimes this is ok, but often if o is null, you want s to be null as well.

Enter ‘as’. as is like a typecast that will return null if needed.

Your code would then be:

string s = o as string;

This is why you can’t use ‘as’ with value types (int, bool, structs, etc.)–they can’t take on the value of null in the first place. With .Net 2.0, however, the rules change…