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

拜拜、爱过 提交于 2020-12-30 07:28:23

问题


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

string text;

回答1:


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.



来源:https://stackoverflow.com/questions/55607785/what-is-the-default-value-of-non-nullable-reference-types-in-c-sharp-8

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!