Reputation: 49311
An idle question on language design, see "Does C# have a right hand if like Perl".
For example, in recent C family languages
z = foo ( a, b, c );
a
is evaluated, then b
, then c
, so left-to-right.
z = a ? b : c;
a
is evaluated, then either b
or c
, so left-to-right order.
In Python, you write a conditional expression as
z = b if a else c
so the order is the same - a
,then b
or c
, but it's not left-to-right.
Strict left-to-right ordering was put into Java to simplify the language; ordering is implementation dependent in C or C++.
Upvotes: 4
Views: 773
Reputation: 171814
I assume you're actually referring to operators that are right-associative, which are operators that act on the right side of the operators.
Most operators in C# are left-associative, except for:
Technically, there's another one: the ternary operator (a ? b : c), but that's such a different beast that it hardly qualifies as a right-associative operator.
Upvotes: 0
Reputation: 8402
No it doesn't check the MS C# lang spec or the ECMA334 spec (chapter 14)
Upvotes: 3
Reputation: 700372
You forgot to put any actual question in your question... I assume that you mean the title to be the question... ;)
You can use an extension and a delegate to make something that looks like a right-to-left evaluation. Actually it's still evaluated from left to right, but the code to the left is put in a delegate and only used based on the result of the condition on the right.
You can make an extension to the Action delegate with the name If.
public static class PostCondition {
public static void If(this Action action, bool condition) {
if (condition) action();
}
}
Now you can make a delegate, cast it to Action, and call the If method on it:
((Action)(() => Console.WriteLine("Yes"))).If(true);
It get's a bit cleaner if you divide it into two statements:
Action writeYes = () => Console.WriteLine("Yes");
writeYes.If(true);
Still, it's not really an improvement over the regular if statement anyway...
Upvotes: 0
Reputation: 564441
Assignment is (sort of) right to left:
int a = b + c;
b+c gets evaluated, then assigned to a.
In general, though, the C# designers have purposely tried to keep most things left->right. A great example is LINQ. Here, instead of going with the traditional SQL ordering (SELECT XXX FROM XXX), they purposely reordered the query to be more left->right.
// Note the left->right ordering:
var results = from member in collection where member.element == condition select member;
// Which is equivelent to:
var resultsNonLinq = collection.Where().Select();
This is part of why I like C# - the consistency in the language is very refreshing, especially when compared to some languages like perl where there is purposely many ways of doing simple things.
Upvotes: 3
Reputation: 180808
C# has the ternary operator:
result = a == b ? c : d
is equivalent to
if (a == b)
result = c;
else
result = d;
It's not strictly right to left, but it does reduce the amount of needed code.
Upvotes: 0