Home >

Proper use of the “as” operator in C"#

29. July 2010

Too often I see C#-code like this:

SomeClass typedVariable = myObject as SomeClass;
typedVariable.SomeMethod();

This is a contradictive statement because basically what it’s doing is this:

“Try to cast whatever is in “myObject” as a “SomeClass”. If it succeeds, call “SomeMehtod”; and if it fails, call SomeMetod”

Probably what the author meant was this:

SomeClass typedVariable = (SomeClass)myObject;

The problem with the first code snippet is that the exception is thrown at the method invocation instead of where the failed conversion actually took place. This can obviously be very confusing when debugging the code and the two lines aren’t right next to each other. But either way, it’s just wrong.

Even if the “as”-operator looks more esthetic to some, please realize that it too has a special purpose in life. MSDN explains it pretty well:
“The as operator is like a cast except that it yields null on conversion failure instead of raising an exception.”

To make the first code snippet make sense using the “as”-operator, we could change it to:

SomeClass typedVariable = myObject as SomeClass;
if (typedVariable == null)
    Console.WriteLine("Conversion failed");
else
{
    Console.WriteLine("We are good to go!");
    typedVariable.SomeMethod();
}
Now we're actually making use of the operator as intended. Without the null-check anywhere, it’s pointless to use the “as”-operator.