はい、そうです。ildasm
または Reflector を使用してコードを検査することで、これを確認できます。
static void Main(string[] args) {
string s = "A" + "B";
Console.WriteLine(s);
}
に翻訳されます
.method private hidebysig static void Main(string[] args) cil managed {
.entrypoint
// Code size 17 (0x11)
.maxstack 1
.locals init ([0] string s)
IL_0000: nop
IL_0001: ldstr "AB" // note that "A" + "B" is concatenated to "AB"
IL_0006: stloc.0
IL_0007: ldloc.0
IL_0008: call void [mscorlib]System.Console::WriteLine(string)
IL_000d: nop
IL_000e: br.s IL_0010
IL_0010: ret
} // end of method Program::Main
さらに興味深いが、関連することが起こります。アセンブリに文字列リテラルがある場合、CLR はアセンブリ内の同じリテラルのすべてのインスタンスに対して 1 つのオブジェクトのみを作成します。
したがって:
static void Main(string[] args) {
string s = "A" + "B";
string t = "A" + "B";
Console.WriteLine(Object.ReferenceEquals(s, t)); // prints true!
}
コンソールに「True」と出力されます。この最適化は、ストリングインターニングと呼ばれます。