Paulo Morgado

.NET Development & Architecture

Recent Articles

view all

Events

Projects

Recent Readers

Visitor Locations

Visitor Locations

Disclaimer

The opinions and viewpoints expressed in this site are mine and do not necessarily reflect those of Microsoft, my employer or any community that I belong to. Any code or opinions are offered as is. Products or services mentioned are purchased by me, made available to me by my employer or the manufacturer/vendor which doesn't influence my opinion in any way.

Breaking Changes In Argument List Evaluation In C# 5.0

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 (…)”.

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

Comments

The Morning Brew - Chris Alcock » The Morning Brew #1148 said:

Pingback from  The Morning Brew - Chris Alcock  » The Morning Brew #1148

# July 18, 2012 4:26 AM

Chris Eargle said:

I would modify "expression evaluation should be avoided in argument lists" to "expression evaluation that changes state should be avoided in argument lists." It works perfectly fine if the evaluation causes no side effects.

# July 18, 2012 11:59 AM

Paulo Morgado said:

Chris,

I thought about that.

Would you consider DateTime.Now something that changes state? Or is it something where state changes by itself?

And you may not have state changing statements, but than add one, and later another...

The safest is never doing it. But like most superlatives, it might be overkill.

# July 18, 2012 9:59 PM

Friday Links #212 | Blue Onion Software * said:

Pingback from  Friday Links #212 | Blue Onion Software *

# July 20, 2012 6:49 PM
Leave a Comment

(required) 

(required) 

(optional)

(required)