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_Notes { get; set; }
//Create instance of foo
foo myFoo = new foo();
//Get value of Address_Notes
var notesValue = myFoo.Address_Notes; //Returns null
Am I crazy to think that a non-nullable string's value should default to String.Empty
? Is there a standard way of forcing this behavior, other than a custom getter?
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: string.Empty means "value is empty" or "value does not exists".
In a nullable aware context: 1 A variable of a reference type T must be initialized with non-null, and may never be assigned a value that may be null. 2 A variable of a reference type T? may be initialized with null or assigned null, but is required to be checked against null before de-referencing. 3 A variable m of type T? ...
The variables notNull and nullable are both represented by the String type. Because the non-nullable and nullable types are both stored as the same type, there are several locations where using a nullable reference type isn't allowed. In general, a nullable reference type can't be used as a base class or implemented interface.
You can also declare nullable value types. Nullable reference types are available beginning with C# 8.0, in code that has opted in to a nullable aware context. Nullable reference types, the null static analysis warnings, and the null-forgiving operator are optional language features. All are turned off by default.
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).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With