Declare Non-Nullable Variables, Parameters, and Check for Null
Learn about nullable reference types in C# and how they allow static analysis of code for potential null value issues in reference types.
We'll cover the following
If we enable nullable reference types and we want a reference type to be assigned the null value, then we will have to use the same syntax as making a value type nullable, that is, adding a ?
symbol after the type declaration.
Enabling nullable reference types
So, how do nullable reference types work? Let’s look at an example. When storing information about an address, we might want to force a value for the street, city, and region, but the building can be left blank, that is, null:
Step 1: In NullHandling.csproj
, add a class file named Address.cs
.
Step 2: In Address.cs
, add statements to declare an Address
class with four fields, as shown in the following code:
Get hands-on with 1400+ tech skills courses.