What is the difference between String.Empty and “” (empty string)?

后端 未结 17 1962
礼貌的吻别
礼貌的吻别 2020-11-22 03:25

In .NET, what is the difference between String.Empty and \"\", and are they interchangable, or is there some underlying reference or Localization i

17条回答
  •  情书的邮戳
    2020-11-22 04:12

    Another difference is that String.Empty generates larger CIL code. While the code for referencing "" and String.Empty is the same length, the compiler doesn't optimize string concatenation (see Eric Lippert's blog post) for String.Empty arguments. The following equivalent functions

    string foo()
    {
        return "foo" + "";
    }
    string bar()
    {
        return "bar" + string.Empty;
    }
    

    generate this IL

    .method private hidebysig instance string foo() cil managed
    {
        .maxstack 8
        L_0000: ldstr "foo"
        L_0005: ret 
    }
    .method private hidebysig instance string bar() cil managed
    {
        .maxstack 8
        L_0000: ldstr "bar"
        L_0005: ldsfld string [mscorlib]System.String::Empty
        L_000a: call string [mscorlib]System.String::Concat(string, string)
        L_000f: ret 
    }
    

提交回复
热议问题