.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

13 Comments

  • Excellent tip. Thank you!

  • 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.

  • @ 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.

  • @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

  • Great placement. I was checking constantly this blog and I am impressed! Fantastically helpful in rank chiefly the last parcel I care for such facts much. I was seeking this exacting in rank for a long schedule. Express gratitude you and clear luck.

  • My idea of a blog entry definitely, good work on the splendid piece you have done on checking the topic down in to manageable data.

  • I found 4 sets (Only two of those captured in individual width your Dillard's).My wife and i sorted someone from the on the website personally andf the other to obtain individual youngster, firstly I thought I am unable to know My group is close to topay that much to have a 3yr olds blade and soul gold, however i sorted each of them no matter what. That she admired each of them firstly and thus wore each of them many, to make certain that made it easier to. In that case your sweetheart control originated over allowed to remain blade and soul gold and so the most effective is now shut off a tad too, a bit of discouraging that possibly less long lived on your inexperienced user and yet whole Absolutely love each of them

  • Wow, incredible blog layout! How long have you been blogging for? you make blogging look easy. The overall look of your website is great, as well as the content!

  • These blade & soul gold are awesome and really flexible.

  • Adore happens to be fallible here at commence, however it germinates much more powerful with age when it's accurately fertilized.

  • Need bought so many kind comments a neverwinter power leveling which has equally brought on good friends to purchase a couple.

  • It's my job to provide a 9 1/2 and then purchased a good 8- cheap wow gold healthy absolutely. Highly excellent, in addition to my personal your feet are not popular and / or specialized. Great product Endorse!

  • I like these neverwinter power leveling. I purchased them just before . Pretty nice.

Comments have been disabled for this content.