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

后端 未结 17 1531
礼貌的吻别
礼貌的吻别 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:07

    what is the difference between String.Empty and "", and are they interchangable

    string.Empty is a read-only field whereas "" is a compile time constant. Places where they behave differently are:

    Default Parameter value in C# 4.0 or higher

    void SomeMethod(int ID, string value = string.Empty)
    // Error: Default parameter value for 'value' must be a compile-time constant
    {
        //... implementation
    }
    

    Case expression in switch statement

    string str = "";
    switch(str)
    {
        case string.Empty: // Error: A constant value is expected. 
            break;
    
        case "":
            break;
    
    }
    

    Attribute arguments

    [Example(String.Empty)]
    // Error: An attribute argument must be a constant expression, typeof expression 
    //        or array creation expression of an attribute parameter type
    

提交回复
热议问题