C# + operator calls string.concat function? [duplicate]

懵懂的女人 提交于 2019-12-05 10:22:43

So why does concat gets called when we use + for combining strings?

Section 7.7.4 of the C# specification, "Addition operator", defines a binary addition operator for strings, where the operator returns the concatenation of the operands.

The definition of System.String in the CLI specification includes several Concat overloads, but no + operator. (I don't have a definitive answer explaining that omission, but I suppose it's because some languages define operators other than + for string concatenation.)

Given these two facts, the most logical solution for the C# compiler writer is to emit a call to String.Concat when compiling the +(string, string) operator.

The code

    public string Foo(string str1, string str2)
    {
        return str1 + str2;
    }

gives the following IL:

IL_0000:  nop
IL_0001:  ldarg.1
IL_0002:  ldarg.2
IL_0003:  call       string [mscorlib]System.String::Concat(string, string)
IL_0008:  stloc.0
IL_0009:  br.s       IL_000b
IL_000b:  ldloc.0
IL_000c:  ret

The compiler (at least, the one in Visual Studio 2010) does this job and there is no + overloading.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!