Do string literals get optimised by the compiler?

EDIT: While I strongly suspect the statement below is true for all C# compiler implementations, I’m not sure it’s actually guaranteed in the spec. Section 2.4.4.5 of the spec talks about literals referring to the same string instance, but it doesn’t mention other constant string expressions. I suspect this is an oversight in the spec – I’ll email Mads and Eric about it.


It’s not just string literals. It’s any string constant. So for example, consider:

public const string X = "X";
public const string Y = "Y";
public const string XY = "XY";

void Foo()
{
    string z = X + Y;
}

The compiler realises that the concatenation here (for z) is between two constant strings, and so the result is also a constant string. Therefore the initial value of z will be the same reference as the value of XY, because they’re compile-time constants with the same value.

EDIT: The reply from Mads and Eric suggested that in the Microsoft C# compiler string constants and string literals are usually treated the same way – but that other implementations may differ.

Leave a Comment