Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

BODMAS principle in .NET

Tags:

c#

.net

math

vb.net

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.

like image 219
m.edmondson Avatar asked Jan 20 '12 11:01

m.edmondson


3 Answers

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/

like image 198
Eric Lippert Avatar answered Sep 23 '22 16:09

Eric Lippert


http://msdn.microsoft.com/en-us/library/aa691323(v=vs.71).aspx

like image 32
linkerro Avatar answered Sep 23 '22 16:09

linkerro


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.

like image 40
Dave Avatar answered Sep 22 '22 16:09

Dave