The Wiert Corner – irregular stream of stuff

Jeroen W. Pluimers on .NET, C#, Delphi, databases, and personal interests

  • My badges

  • Twitter Updates

  • My Flickr Stream

  • Pages

  • All categories

  • Enter your email address to subscribe to this blog and receive notifications of new posts by email.

    Join 1,974 other followers

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

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.

 
%d bloggers like this: