Kids sometime play something known as the "Chinese whispers". One person whispers something into the ear of the person at his or her side, that person repeats the message to the next person and so on. In the end the message returns, often distorted, to the person who started.

Luckily, code (typically) does not interpret the message, but rather passes it on in exactly the same form. C# allows chaining assignments in a way that at first glance looks like a variation of the whispering game (but without the fun of the distorted message):

int x, y z;
x = y = z = 42;

The result of the code above is that x, y and z will all have the value 42. So far it seems quite straightforward, right?

Now, consider the following code:

class Foo
{
    public int Value { private get; set; }
}

class Program
{
    public static void Main(string[] args)
    {
        Foo x = new Foo();
        Foo y = new Foo { Value = x.Value = 5 };
        Console.WriteLine(y);
    }
}

Do you see anything odd? x.Value is assigned the value of 5, but what is assigned to y.Value? If you examine the code, you will see that Foo.Value is write-only from outside the Foo class, so the code in Program.Main can't possibly read the value from x.Value in order to assign it to y.Value.

What happens behind the scenes here is that the value on the right-hand side of the expression (in this case the integer 5) is pushed onto the evaluation stack once for each assignment found to its left. Then each assignment is performed by popping the next value off the evaluation stack. So in the example Foo y = new Foo { Value = x.Value = 5 }; the integer 5 is pushed twice onto the evaluation stack, the code pops a value off the stack and assigns it to x.Value and then it pops the next value off the stack and assigns it to y.Value.

So in contrast to the Chinese whispers game, chained assignments is more like the first person whispering the message to each of the other persons directly.

kick it on DotNetKicks.com


I am working for a great consultancy company called Diversify, located in Sweden. We are hiring skilled .NET developers. If you are interested, don't hesitate to get in touch with me.

Comments

September 3. 2010 18:39

trackback

Not the Chinese whispers (chaining assigments in C#)

You've been kicked (a good thing) - Trackback from DotNetKicks.com

DotNetKicks.com