Click here to Skip to main content
12,556,077 members (59,383 online)
Click here to Skip to main content
Add your own
alternative version


11 bookmarked

Breaking Changes in Argument List Evaluation in C# 5.0

, 30 Jul 2012 CPOL
Rate this:
Please Sign up or sign in to vote.
In C# 4.0 there was an error in the C# compiler in the order of the evaluation of the arguments in argument lists.

The C# Language Specification states on § that “(…) the expressions or variable references of an argument list are evaluated in order, from left to right (…)”.free hit counters

So, when this code is compiled with the C# 4.0 compiler:

static void M(
    int x = 10,
    int y = 20,
    int z = 30)
        "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


This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


About the Author

Paulo Morgado
Software Developer (Senior) Paulo Morgado
Portugal Portugal

You may also be interested in...


Comments and Discussions

GeneralMy vote of 5 Pin
johannesnestler26-Jul-12 6:05
memberjohannesnestler26-Jul-12 6:05 
GeneralRe: My vote of 5 Pin
Paulo Morgado26-Jul-12 8:23
memberPaulo Morgado26-Jul-12 8:23 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

| Advertise | Privacy | Terms of Use | Mobile
Web01 | 2.8.161021.1 | Last Updated 30 Jul 2012
Article Copyright 2012 by Paulo Morgado
Everything else Copyright © CodeProject, 1999-2016
Layout: fixed | fluid