Wednesday 5 May 2010

Associativity of '+' in C#

Okay, so whose bright idea was this?

const int
x = 1, y = 2, z = 4, answer = x + y + z;

Console.WriteLine("the answer is " + answer);
Console.WriteLine(x + y + z + " is the answer");
Console.WriteLine("the answer is " + x + y + z);
Console.WriteLine("the answer is " + (x + y) + z);
Console.WriteLine("the answer is " + x + (y + z));
Console.WriteLine("the answer is " + (x + y + z));
Console.ReadKey();

Output:

the answer is 7

7 is the answer
the answer is 124
the answer is 34
the answer is 16
the answer is 7

How did I get as far as C#4.0 without noticing this? And why didn't you tell me sooner? Where are my car keys?

There must have been a moment, during my first reading of the C#1.0 spec, when I read about the object concatenation operator '+' and its ability to join e.g. strings to numerics. Guess I shrugged it off, perhaps thinking crazy Javascript behaviour, certainly won't be using that! Now that it's resurfaced in a colleague's code, I feel so repulsed that - at least until they remove it from the compiler - I'm considering a career change.

No, not to another language, platform, or whatever. I mean maybe to something outdoors, like highway maintenance. Or else... a laundromat. Yes. Yes, that would be cleansing.

One of the best things about this language has always been the number of gotchas that it has removed from our daily lives, when compared with something like C++. Like unintentional fall-through in a switch block. Unfettered operator overloads. Mandatory destructors. Dereferencing with a choice of operators! Multiple inheritance. Arrays as unsafe pointers. Header files and multiple points of declaration. Et cetera, ad nauseam.

But I mean, really. Failure of associativity adding integers. Sheeesh.

No comments:

Post a Comment