BODMAS principle in .NET

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/

Tags:

C#

.Net

Vb.Net

Math