Monday, October 29, 2007 2:59 PM srkirkland

.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;
}
 
//Is equivalent to
 
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://msdn2.microsoft.com/en-us/library/cscsdfbt(vs.71).aspx confirmed this, and even offered up the following explanation.

expression as type
 
//is equivalent to
 
expression is type ? (type)expression : (type)null
  
                  
            Filed under: , , 
    

Comments

# re: .NET 2.0 Cast operator vs. As operator

Tuesday, October 30, 2007 9:39 AM by Edwin

Excellent tip. Thank you!

# Links from the Sharpside [10.30.07]

Wednesday, October 31, 2007 12:47 AM by Tales from the SharpSide

Links from the Sharpside [10.30.07]

# re: .NET 2.0 Cast operator vs. As operator

Wednesday, October 31, 2007 6:47 AM by steve bohlen

This is a great tool, but it also comes with a pitfall; use of this operator has to be limited to cases where (as in your example) NULL is a valid state for your object -- else you will be 'robbed' of the exception that tells you something is wrong.

I think the VB people have had this behavior for some time in their own cast sytnax as they always had to choose betw 'obj AS type' and 'CType(obj, type)' syntaxes that (I seem to recall from my VB.NET days) accomplish the same distinction you are mentioning here since VB.NET lacks the more terse '(type)obj' C# typical cast syntax.

# re: .NET 2.0 Cast operator vs. As operator

Tuesday, November 25, 2008 12:05 PM by A Coder

You took 4 lines of code that were clear, obvious and easily read and turned it into a single line that is convoluted, not obvious and would likely benefit from a comment.

I will take each and every oppertunity to point out each and every time: you are buying into a false economy. Code is written once, it is read an infinite number of time. The 2 cents you saved in writing your code is going to cost you dollars in read-time.

Code is not for computers. Code is not for computers. Code is not for computers. Code is for humans. The first thing a computer does is turn our nonsense into something it can comprehend. You should be writing code for human consumption. Period.

# re: .NET 2.0 Cast operator vs. As operator

Wednesday, December 10, 2008 6:42 PM by CBP

@ A Coder

Many people would disagree with you. Once you get used to reading the ?? syntax, the concise version of the code can be read much more quickly and visualised more easily. It becomes a pattern that the mind can consume in one chunk.

Using the ?? syntax also has extra layers of implicit meaning that can  reveal the programmer's intention more clearly.

That said, if your target audience is beginner programmers (which it often is), then the more verbose syntax may be preferable.

# re: .NET 2.0 Cast operator vs. As operator

Monday, January 05, 2009 8:41 AM by t

@A Coder, CBP

Got to say, I agree with CBP.

I have been coding a few years, and can still remember the time when people showed my tertiary ops, for me to dismiss it as harder than necessary to understand.. however, when you learn it, and see it enough times, it is definately much much easier to read.

T x

# re: .NET 2.0 Cast operator vs. As operator

Thursday, January 08, 2009 12:56 AM by Yashoda

Thank you! I was very happy by using this as it saved a lot of lines of my code. And removed the headache of handling an exception in type casting :)

Leave a Comment

(required) 
(required) 
(optional)
(required)