Non-Nullable String Initializes as Null

前端 未结 4 936
醉话见心
醉话见心 2021-01-18 02:20

I trying to understand why a non-nullable string initializes to null instead of an empty string. For example:

//Property of class foo
public string Address_N         


        
4条回答
  •  耶瑟儿~
    2021-01-18 03:19

    Since you are using properties to get the string values, another option is to return string.Empty if it is in fact null.

    //Property of class foo
    private string _address_Notes;
    public string Address_Notes 
    { 
        get { return _address_Notes ?? string.Empty; } 
        set { _address_Notes = value; }
    }
    

    A much better solution would be to initialise the string to string.Empty (if that is your expected behaviour). You can do this in C# 6+ as follows:

    public string Address_Notes { get; set; } = string.Empty;
    

    This way it's a one off initialisation rather than a check on every request.

提交回复
热议问题