C#: combining “adding `char` and `int` and “`a += b` means `a = a + b`, but `a += b + c` does not mean `a = a + b + c`”.
Posted by jpluimers on 2013/07/18
A while ago, I wrote about .NET/C# duh moment of the day: “A char can be implicitly converted to ushort, int, uint, long, ulong, float, double, or decimal (not the other way around; implicit != implicit)”.
There is another duh moment having to do with the various C# operators like += which is being described as being
a += b
is equivalent to
a = a + b
You might think that this also holds:
a += b + c
is equivalent to
a = (a + b) + c
But Eric Lippert has explained this is not the case: it is equivalent to:
a = a + (b + c)
In his explanation, he also shows the confusion can get you very surprising results if you mix string, chars and ints in the expression: depending on the statement and ordering, you either concatenate characters, or add ints to characters.
He also recommends you should not do concatenation: either use String.Format, or StringBuilder. I totally agree with that.
Recommended reading!
–jeroen
Leave a Reply