The answer to the string concatenation puzzle

Earlier on FAIC I asked for code that parses as an expression that produces different results for

s = s + expr;

and

s += expr;

This is a pretty easy puzzle; the answers posted in the comments could largely be grouped into two buckets. The first, which is a bit silly, are expressions which always produce a different value, so of course they produce different results in those two cases.

s = s + Guid.NewGuid();

produces a different result than

s += Guid.NewGuid();

but then again, it also produces different results every time you call

s += Guid.NewGuid();

so that’s not a particularly interesting answer.

Continue reading

Advertisements

A string concatenation puzzle

Happy Canada Day everyone! I’m back from a fabulous week in California and looking forward to taking a break from giving PowerPoint presentations.

Today, to follow up on my recent series on string concatenation, here’s a fairly easy little puzzle. I have a perfectly ordinary local variable:

string s = "";

Can you come up with some code that parses as a legal expression such that the statements

s = s + your_expression;

and

s += your_expression;

are both legal but produce completely different results in s? Post your proposals in the comments and I’ll give my answer later this week.

String concatenation behind the scenes, part one

The first algorithm I ever worked on in the C# compiler was the optimizer that handles string concatenations.(Unfortunately I did not manage to port these optimizations to the Roslyn codebase before I left; hopefully someone will get to that!) It’s all pretty straightforward, but there are a few clever bits that I thought I might discuss today.

Continue reading