19 June 2007

The CSharp AS Keyword

by mo

Let’s say we have the following code:

object o = new string('8', 1);

There are a few ways that we can work with this object as a string. We can do a direct cast to string, like this:

  try {
    string s2 = (string)o;
    Console.WriteLine("is string");
  } catch(InvalidCastException) {
    Console.WriteLine("is not string");

This isn’t the most optimal way, because raising and catching exceptions is heavy. An alternative is to check if it is a string before casting using the “is” operator. Like this…

  if( o is string ) {
    string s2 = (string)o;
    Console.WriteLine("is string");
  else { Console.WriteLine("is not string");}

This is better but still not great, we have to implicity cast twice, which is slightly expensive as well. My preferred method is to use the “as” keyword.

string s = o as string;
Console.WriteLine(( null != s) ? "is String" : "is not string");

This will attempt to cast “o” to type string. If it is not of type string then it will return null. The benefit of this is that we can cast once, and not have to deal with catching exceptions.

For more information on the “as” operator check out MSDN