|
|
Posted on 2022-3-26 16:40:21
|
|
|
|

Prior to C# 8.0, all reference types could be null. Null reference types refer to a set of features introduced in C# 8.0 that can be used forMinimize the likelihood that your code will cause runtime throws。 Nullable reference types include three features to help avoid these exceptions, including the ability to explicitly mark reference types as nullable:
- Optimized static flow analysis to determine if a variable is null before it is unreferenced.
- Attributes that are used to annotate the API so that Stream Analytics determines the null state.
- Variable annotations that developers can use to explicitly declare the expected null state of a variable.
Null state analysis and variable annotations are disabled by default for existing projects, which means that all reference types are still nullable. Starting with .NET 6, these features are enabled by default for new projects.
Documentation:The hyperlink login is visible.
What a reference type that can be null is to doMinimize the chance that your application will throw a System.NullReferenceException at runtime。
In a project I am developing with .NET 6, I create a Name property for a new property that prompts me with the following warning:
When exiting the constructor, the non-nullable property "Name" must contain a non-null value. Consider declaring the property as can be null.
Although it is a warning, it is very annoying! How to fix this warning? The default value for assignment is an empty string, and the code is as follows:
That is, when the property is not manually assigned, the default value of the property is an empty string.
When using a local variable,The type is string? may also generate warnings, as shown in the figure below:
solution, determine if the variable is null before using it, and if it is, don't execute the code below, or you thinkThe variable can never be null, can be usedArgumentNullException.ThrowIfNull(assemblyFullName); Warnings can also be removed! In other words, if the variable is null, it will throw an exception directly during runtime!
Summary: C# 8.0 introduced this feature, and I personally feel that it is to improve the rigor of developers and avoid making some low-level mistakes.
For more method solutions that can be null, please refer to:The hyperlink login is visible.
|
Previous:Query the remote address of the current project's GitNext:ASP.NET Core (twelve) front-end JS, CSS bundling, and compression
|