Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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

string text;
like image 311
Hrant Khangulyan Avatar asked Apr 10 '19 08:04

Hrant Khangulyan


People also ask

What is non-nullable value type?

Nullable variables may either contain a valid value or they may not — in the latter case they are considered to be nil . Non-nullable variables must always contain a value and cannot be nil . In Oxygene (as in C# and Java), the default nullability of a variable is determined by its type.

What is default of nullable type?

The default value of a nullable value type represents null , that is, it's an instance whose Nullable<T>. HasValue property returns false .

What is non-nullable type in C#?

You specify that if the parameter is not null, the method does not return null. The compiler will recognize the attribute and will use it as a help to know whether it should show an error or not.

Is nullable type reference type?

Nullable reference types aren't new class types, but rather annotations on existing reference types. The compiler uses those annotations to help you find potential null reference errors in your code. There's no runtime difference between a non-nullable reference type and a nullable reference type.


1 Answers

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.

like image 166
Lasse V. Karlsen Avatar answered Sep 18 '22 11:09

Lasse V. Karlsen