Let’s say we have the following code:

1 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:

1 try {
2     string s2 = (string)o;
3     Console.WriteLine( "is string" );
4   } catch( InvalidCastException ) {
5     Console.WriteLine( "is not string" );
6   }

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…

1 if( o is string ) {
2     string s2 = (string)o;
3     Console.WriteLine( "is string" );
4   }
5   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

comments powered by Disqus