Non-Nullable String Initializes as Null

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

提交回复
热议问题