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
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).
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.
A string is a reference type, it's always nullable.
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.