Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Non-Nullable String Initializes as Null

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?

like image 213
James Hill Avatar asked Oct 19 '11 13:10

James Hill


People also ask

Is it possible to initialize a string to null?

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".

How to initialize a variable in a nullable context?

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? ...

What is the difference between notnull and nullable in Java?

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.

Can you declare a nullable value type in C?

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.


1 Answers

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).

like image 50
Jamiec Avatar answered Oct 01 '22 14:10

Jamiec