I discovered today that the .NET framework follows the BODMAS order of operations when doing a calculation. That is calculations are carried out in the following order:
However I've searched around and can't find any documentation confirming that .NET definitely follows this principle, are there such docs anywhere? I'd be grateful if you could point me in the right direction.
Note that C# does not do the BODMAS rule the way you learned in school. Suppose you have:
A().x = B() + C() * D();
You might naively think that multiplication is "done first", then the addition, and the assignment last, and therefore, this is the equivalent of:
c = C();
d = D();
product = c * d;
b = B();
sum = b + product;
a = A();
a.x = sum;
But that is not what happens. The BODMAS rule only requires that the operations be done in the right order; the operands can be computed in any order.
In C#, operands are computed left-to-right. So in this case, what would happen is logically the same as:
a = A();
b = B();
c = C();
d = D();
product = c * d;
sum = b + product;
a.x = sum;
Also, C# does not do every multiplication before every addition. For example:
A().x = B() + C() + D() * E();
is computed as:
a = A();
b = B();
c = C();
sum1 = b + c;
d = D();
e = E();
product = d * e;
sum2 = sum1 + product;
a.x = sum2;
See, the leftmost addition happens before the multiplication; the multiplication only has to happen before the rightmost addition.
Basically, the rule is "parenthesize the expression correctly so that you have only binary operators, and then evaluate the left side of every binary operator before the right side." So our example would be:
A().x = ( ( B() + C() ) + ( D() * E() ) );
and now it is clear. The leftmost addition is an operand to the rightmost addition, and therefore the leftmost addition must execute before the multiplication, because the left operand always executes before the right operand.
If this subject interests you, see my articles on it:
http://blogs.msdn.com/b/ericlippert/archive/tags/precedence/
http://msdn.microsoft.com/en-us/library/aa691323(v=vs.71).aspx
http://msdn.microsoft.com/en-us/library/aa691323%28v=vs.71%29.aspx details all the priorites and doesn't quite tally with your list.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With