Quickly understand the language features of nullable reference type in C # 8.0

Time:2021-7-20

Visual C # 8.0 introducesNullable reference type(nullable reference type), through the powerful functions provided by the compiler, helps developers to avoid the code problems caused by null references as much as possible. Here I’ll give you a brief introduction to the basic content of nullable reference types.
It may not be easy to understand when you first come into contact with this language feature. Reference type is nullable. Why should we introduce the concept of nullable reference type?In fact, from the perspective of compiler, developers are required to consider whether a variable may be empty when programmingSo as to reduce the code errors caused by null references as much as possible.
It is assumed that there are the following categories:

class Student
{
    public Student(string name, DateTime dayOfBirth)
        => (Name, DayOfBirth) = (name, dayOfBirth);

    public string Name { get; set; }

    public DateTime DayOfBirth { get; set; }

    public string Notes { get; set; }
}

This class defines the basic information of a “student” entity. For the sake of simplification, only a few attributes need to be discussed are listed here

  • Name: Student’s name
  • Dayofbirth: Student’s birthday
  • Notes: Notes on student information

Suppose we have two operations: find out all the students with remarks among all the students, and sort all the students by name. It is easy to use LINQ in C #

var studentsHasNotes = students.Where(s => s.Notes.Length > 0);

And:

var orderedStudents = students.OrderBy(s => s.Name);

So far no problem, the program can run normally. However, after careful code review, it is not difficult to find that in the code for obtaining all students with remarks (that is, in the first paragraph above), there may be an exception of null reference, because for a “student” entity, its notes attribute may be null.
Now let’s open the language feature of “nullable reference type”. There are two main ways to open it: you can edit the csproj project file at the project level to set it, or you can use the # nullable precompile instruction to implement it

  • Edit csproj project file, addenableThen:
    image
  • It is implemented by # nullable precompile instruction. You only need to add # nullable instruction to the code where you need it
    image

After enabling the language feature of “nullable reference type”, you will find that a warning appears at the constructor of the student class above, indicating that the nullable “notes” property needs to have a nullable value when the constructor is completed. It is recommended to set it to nullable string type. Why does the compiler only prompt that notes may be empty instead of the name property? Because the name has been assigned in the constructor, the name cannot be empty for any student object, but not notes.

image

Name cannot be empty? Isn’t it a string type? What if it’s empty in the code? Don’t worry, the compiler won’t allow this:

image

Here, we set the notes property tostring?Type, so you will find that the warning information on the constructor is gone, because we allow the student object to have no notes data. However, in the operation of “find all students with notes”, a warning will appear, indicating that notes may be empty

image

Therefore, you will find that after the language feature of nullable reference type is enabled, we need to carefully examine the attributes of each reference type in student type to see if it is possible to be empty in practical application. If it is possible to be empty, use nullable reference type to define attributes. After that, the compiler will help you analyze where there may be empty references.

In the above example of “find all students with notes”, if you think notes will not be empty, you can also use “!” Operator to override compiler warnings, such as:

image

Now the popular. Net open source frameworks have basically supported the nullable reference type, and if you are a developer of open source frameworks, it is strongly recommended to enable this language feature in your framework to avoid the nullable reference problem as much as possible. For example, if you enable the nullable reference type feature in your code, when you inherit from the jsonconverter class of newtonsoft.json, you will find that you must use the function overload of nullable reference type:

image

However, if you do not enable the nullable reference type feature, when you inherit from the jsonconverter class of newtonsoft.json, you will find that the signature of the overloaded function is the same as before:

image

Well, there are so many introductions to C # 8.0’s “nullable reference type”. I believe it has basically summarized its main points and usage, which should be enough in daily development.