What is the default value of Non-Nullable reference types in C# 8?
Asked Answered
I

1

8

If I enable nullable reference types, what will be the value of the following string if I declare it like so?

string text;
Immesh answered 10/4, 2019 at 8:14 Comment(1)
That was also my question. If reference types are non-nullable why do they have null as their default values lolRosannrosanna
S
13

The value will be null.

Bear in mind that the new system for nullable reference types will only warn you about problems, it will not give you an error, and that means that the code will still compile, with warnings.

If you declare this class:

public class Test
{ 
    private string text;
}

You'll get this warning for your class:

CS8618: Non-nullable field 'text' is uninitialized.

However, the code still compiles.

So to (again) answer your question, the default value for that field will be null.

Note: If you use that statement to declare a local variable, the answer is that it will not have a value, it will be considered definitely unassigned, and you're not allowed to read from that variable until you have code in place that makes it definitely assigned first.


As for warnings vs. errors, you can opt-in to get them as errors by fiddling with the project options and list the warnings you want to be treated as errors instead.

Syracuse answered 10/4, 2019 at 8:24 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.