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.


2 thoughts on “Conditional Operators

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

  2. 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. ;-)

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s