Throughout many decades of programming, the NullReferenceException has haunted us. Though this exception is easily resolved, the chances that it will occur in other places are very high.

With the introduction of nullable in C# 8.0, the chances of null reference exceptions have become minimal. In this blog, I will walk you through using nullable in your C# programs to avoid Null Reference Exceptions.

Scenario of null reference exception

Let’s first look into a scenario in which the null reference exception occurs. Consider the following class named Commit with the data, username, password, and commit message, and a constructor that initializes only the values of first name and last name.

class Commit { public string UserName { get; set; } public string Password { get; set; } public string CommitMessage { get; set; } public Commit(string userName, string password) { UserName = userName; Password = password; } }

If you create an instance of the class Commit with the constructor and try to get the length of the CommitMessage, you will end up with a null reference exception.

static void Main(string[] args) { Commit initial = new Commit("Suresh", "$trongPassword123"); int messageLength = GetMessageLength(initial); Console.WriteLine(messageLength); } static int GetMessageLength(Commit person) { var commitMessage = person.CommitMessage; return commitMessage.Length; }

Once we find that this code will cause the null reference exception, we can fix it by giving it a null check.

But with the nullable feature, you can identify the occurrence of the exception even before compiling the code. Check out how in the following section.

How to enable C# 8.0

Like I said before, the nullable feature is a part of the C# 8.0 update and you have to confirm that your project is coded with C# 8.0 before proceeding further.

In the latest version of Visual Studio, the provision to change the language version in the project’s properties is blocked.

On checking further with the provided link, we found that, when the target framework of the project is either .NET Core 3.x or .NET Standard 2.1, the default language version is C# 8.0.

If you use an older framework in your project and still want to try this feature, then you can configure this manually. Edit the project file (*.csproj) and edit the value of the language version tag (<LangVersion>) to be the preview, as illustrated in the following.

<PropertyGroup> <LangVersion>preview</LangVersion> </PropertyGroup>

This will allow you to use the features available in the preview C# language that the compiler supports.

Using the nullable feature

Now, enable the nullable feature for the entire project (you can enable it for a particular class, too). Edit the project file and add the Nullable tag with the value enable.

<PropertyGroup> <OutputType>Exe</OutputType> <TargetFramework>netcoreapp3.0</TargetFramework> <Nullable>enable</Nullable> </PropertyGroup>

This will lead to a warning in the constructor of the Commit class, with the information that the CommitMessage is uninitialized.

It is in the nature of a common developer to avoid warnings and worry only about errors. Here, we are not going to ignore the warning, as it would lead to an exception at run time. So, initialize the CommitMessage with the value null.

Still, it will display a warning. Now, make the CommitMessage property accept null by declaring it as a nullable string (string?).

public string? CommitMessage { get; set; }

The warning will disappear and a new warning will be displayed in the Program.cs class when trying to access the length of the CommitMessage.

Handle this warning by returning 0 if CommitMessage is null. Now there is no chance of null reference exceptions in this program.

static int GetMessageLength(Commit person) { var commitMessage = person.CommitMessage; if (commitMessage is null) return 0; return commitMessage.Length; }

Resource

You can find a copy of this project in this GitHub location.

Conclusion

I hope you enjoyed learning a new concept that is available with the C# 8.0 language version. Use this feature in your project and get rid of null reference exceptions.

Please be aware that Syncfusion offers a wide variety of developer components for mobile, desktop, and web platforms. Make use of them and develop complex projects in less than half the estimated time.

Happy Coding! #SayNoToNullReference

Reference: