What is the output of the following program?
static void Main()
int result = x() + y() *
static int x()
static int y()
static int z()
We all know that multiplication has a higher precedence then addition.
So for example: 3 + 2 * 3 will be calculated as 3 + (2 * 3) = 3 + 6 = 9.
The result of our simple program is also not very hard to calculate. 3 + (2 * 6) = 15. So, y and z before x. The expected output would be: y z x 15. Or not?
As you can see, the output is x y z 15. Why is that? It’s because operator precedence controls the order in which operators are executed, not the order in which they are evaluated!
Operands are evaluated from left to right. So x is evaluated before y and y is evaluated before z. Then the resulting values are executed, which uses the normal operator precedence we are used to.
In something simple as this, it won’t cause any problems. But suppose that x, y, z act on some class fields and modify them. Then suddenly, your fields would be modified ‘left to right’ and then the result would be calculated with regular operator precedence.
But luckily for us, The C# specification explains it all!