.NET 2.0 Cast operator vs. As operator
When I was converting untyped data values from a SQL database into a custom Business class, I realized that I have to take a special precaution when casting possibly null values. If you try to cast DBNull to some type, you will get an InvalidCastException. When thinking about a solution, I remembered the as operator and decided to do some investigating. Consider the following example:
object objstr = DBNull.Value;
string str1 = (string)objstr; //Cast throws an Exception
string str2 = objstr as string; //No exception is thrown, and str2 == null
The as operator lends very well to using the ?? for writing compact code. Here's a little syntactic sugar:
if ( objstr == DBNull.Value )
{
strResult = "Default";
}
else
{
strResult = (string)objstr;
}
A0
//Is equivalent to
A0
strResult = objstr as string ?? "Default";
So it turns out that the as operator is just like the cast operator except that it yields null on conversion failure instead of throwing an exception. Looking at a MSDN C# Programmer's Reference page http://msdn.microsoft.com/en-us/library/cscsdfbt(vs.71).aspx confirmed this, and even offered up the following explanation.
expression as type
A0
//is equivalent to
A0
expression is type ? (type)expression : (type)null