The C# Language Specification states on §7.5.1.2 that “(…) the expressions or variable references of an argument list are evaluated in order, from left to right (…)”.![free hit counters](https://c.statcounter.com/5780550/0/62f34f0e/1/)
So, when this code is compiled with the C# 4.0 compiler:
static void M(
int x = 10,
int y = 20,
int z = 30)
{
Console.WriteLine(
"x={0}, y={1}, z={2}", x, y, z);
}
static void Main(string[] args)
{
int a = 0;
M(++a, z: ++a);
}
and run, this unexpected output is obtained:
x=2, y=20, z=1
In fact, fixing this compiler flaw was the cause of one of the few breaking changes introduced in C# 5.0.
Using the 5.0 compiler, the expected result is obtained:
x=1, y=20, z=2
To avoid this type of surprises, expression evaluation should be avoided in argument lists.
With this code:
int a = 0;
int i = ++a;
int j = ++a;
M(i, z: j);
the same result is obtained for both C# 4.0 and C# 5.0:
x=1, y=20, z=2