Non-Nullable String Initializes as Null

前端 未结 4 903
醉话见心
醉话见心 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:13

    There is no such thing as a "non-nullable string".

    String is a reference type, so its default value is indeed a null.

    You could get around the issue by setting the value to String.Empty in the constructor for your class (foo).

    0 讨论(0)
  • 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.

    0 讨论(0)
  • 2021-01-18 03:20

    A string is a reference type, it's always nullable.

    0 讨论(0)
  • 2021-01-18 03:21

    String is reference type - values are initialized to null by default.

    You can initialize strings in constructor to string.Empty, and it is best practice to do it, because:

    • null value means "I do not know what is the value"
    • string.Empty means "value is empty" or "value does not exists".

    So, almost every string properties should be (by you) initialized to string.Empty value. Try to read something about "null object pattern". Programming according this principle makes much more readable and bug-proof code.

    0 讨论(0)
提交回复
热议问题