7

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:

  • Brackets
  • Orders
  • Division
  • Multiplication
  • Addition
  • Subtraction

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.

m.edmondson
  • 30,382
  • 27
  • 123
  • 206

4 Answers4

28

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/

Eric Lippert
  • 647,829
  • 179
  • 1,238
  • 2,067
1

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.

Dave
  • 3,581
  • 1
  • 22
  • 25
0

C# doesn't follow the BODMAS rule when it comes to multiplying, division, addition, and subtraction.

  1. Multiply and division have the same priority and will do from left to right.
  2. Addition and division have the next same priority and will do from left to right.

It seems its language-dependent. No standard. So, the results would be different in each programming language. If brackets are used then there will be no issues.

Nithin B
  • 601
  • 1
  • 9
  • 26