Nullable reference types

If you have ever faced an exception while coding in C#, it is likely to have been a null reference exception. Null reference exceptions are one of the most common exceptions a programmer will face while developing applications, so the C# language development team has worked hard to make them easier to understand.

In C#, there are two types of data: value types and reference types. Value types normally have default values when you create them, whereas reference types are, by default, null. Null means that the memory address does not point to any other memory address. When the program tries to find a reference and can't find any, it throws an exception. As developers, we want to ship software that is exception-free, so we try to handle all the exceptions in our code; however, sometimes, it can be really hard to find a null reference exception when developing applications.

In C# 8, the language development team came up with nullable reference types, which means that you can make a reference type nullable. If you do this, the compiler will not allow you to set null to non-nullable reference variables. If you are using Visual Studio, you will also get a warning if you try to set a null value to a non-nullable reference variable.

As this is a new feature and not available in old versions of C#. The C# programming language team came up with the idea of enabling the feature by writing a piece of code, so that the old systems doesn't crash. You can enable this feature for the whole project or for an individual file.

To enable nullable reference types in a code file, you have to place the following code at the top of the source code:

#nullable enable

Let's take a look at an example of a nullable reference type:

class Hello {
public string name;
name = null;
Console.WriteLine($"Hello {name}");
}

If you run the preceding code, you get an exception when trying to print the statement. Try to enable nullable reference types by using the following code:

#nullable enable

class Hello {
public string name;
name = null;
Console.WriteLine($"Hello {name}");
}

The preceding code will show you a warning to the effect that the name can't be null. To make this workable, you have to change the code as follows:

#nullable enable

class Hello {
public string? name;
name = null;
Console.WriteLine($"Hello {name}");
}

By changing the string name to nullable, you are telling the compiler that it's OK to make this field nullable.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.142.98.186