What’s New with C# 8.0 – Nullable Reference Type

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.Advanced Build Setting VS2019

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.Non nullable property warning - C# 8.0

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.Cannot convert null literal - C# 8.0

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.Dereference of a possibly null reference - C# 8.0

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:

Tags:

Share this post:

Related Posts

Comments (4)

Balasubramanian Sundararajan

Great blog post Suresh 👍

Nice explanation. Very good practical example!
One tip, only. You could replace the entire GetMessageLength method with this simple sentence, that is also illustrative of null handling:

int messageLength = commitMessage?.Length ?? 0;

Regards

Hi Vicent,
Thank you so much for your appreciation. Your tip is noted, will use it in the upcoming blogs.
Thanks,
Suresh

really useful

Leave a comment