Omer van Kloeten's .NET Zen

Programming is life, the rest is mere details

News

Omer van Kloeten's Facebook profile

Omer has been professionally developing applications over the past 8 years, both at the IDF’s IT corps and later at the Sela Technology Center, but has had the programming bug ever since he can remember himself.
As a senior developer at NuConomy, a leading web analytics and advertising startup, he leads a wide range of technologies for its flagship products.

Get Firefox


powered by Dapper 

.NET Resources

Articles :: CodeDom

Articles :: nGineer

Culture

Projects

Conditional Operators

The C# spceification declares the Conditional Operator (14.12), otherwise known as the Ternary Operator. It means that you can do this:

int i = (boolean_expression ? j : k);

This is great. Less readable, but great.
A couple of days ago, I thought: "why not go another step?" and came up with this:

int i = try { int.Parse(str); } catch { 0; }
This would help remove the "Use of unassigned local variable" errors and make the code less complicated.
Of course, the usual cases of "if there is more than one line in there, write it in the expanded form" apply.

I'd love to hear comments and suggestions.

Posted: Feb 10 2004, 12:25 AM by Omer van Kloeten | with 5 comment(s)
Filed under:

Comments

Chris McGuirk said:

Frankly, I think the first version is more readable ;)

Also, I'd recommend creating a helper class for the 2nd case, so that you arent duplicating that code all over the place. Oddly enough, the Double class has a TryParse method, which will return a boolean rather than throwing an exception on failure, however none of the other primitive data type wrapper classes have that....odd.
# February 9, 2004 6:19 PM

Scott Mitchell said:

Your second example kind of reminds me of Perl's or statement, when used like:

open(file) or die('File cannot open.');

If the file opens successfully it returns true and short-circuiting stop the die() function from running. If the file cannot be opened, it returns false, so the second half is evaluated, invoking the die() method.

You could have something in C# like:

int i = int.Parse(num) || 0;

This would require a language change, but would kind of be cool. It would make C# more like Perl. Although I can't say we necessarily would want that. ;-)
# February 9, 2004 11:28 PM

Omer van Kloeten said:

Chris - My example was just what it was, an example. I can find tons of other examples, so please don't think this is Parse specific.

Scott - The syntax you offer can't be implemented because it exists today and would cause a build error (int cannot be converted to bool), but this is just me nitpicking. ;)
# February 10, 2004 5:07 AM

TrackBack said:

First post since the move @ .Net Blog
# February 10, 2004 5:13 AM

TrackBack said:

# June 22, 2004 7:18 AM
Leave a Comment

(required) 

(required) 

(optional)

(required)