What’s with C# 8.0 – Nullable Reference Type
Tags: dotnet, csharp, productivity, tutorial
Published: 2019-10-29 12:06:47

---
title: What’s with C# 8.0 – Nullable Reference Type
published: true
date: 2019-10-24 11:00:05 UTC
tags: dotnet, csharp, productivity, tutorial
canonical_url: https://www.syncfusion.com/blogs/post/whats-with-c-8-0-nullable-reference-type.aspx
cover_image: https://thepracticaldev.s3.amazonaws.com/i/a73zingzjj8truhan3d2.png
---

Throughout many decades of programming, the [NullReferenceException](https://docs.microsoft.com/en-us/dotnet/api/system.nullreferenceexception?view=netframework-4.8) 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.

```csharp
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.

```csharp
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](https://www.syncfusion.com/blogs/wp-content/uploads/2019/10/Advanced-Build-Setting-VS2019-1.png)

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 preview, as illustrated in the following.

```xml
<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**.

```xml
<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](https://www.syncfusion.com/blogs/wp-content/uploads/2019/10/Non-nullable-property-warning-1.png)

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](https://www.syncfusion.com/blogs/wp-content/uploads/2019/10/Cannot-convert-null-literal-1.png)

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

```csharp
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](https://www.syncfusion.com/blogs/wp-content/uploads/2019/10/Dereference-of-a-possibly-null-reference-1.png)

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

```csharp
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](https://github.com/SyncfusionExamples/csharp-8.0-nullable-reference-type).

## 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 the half the estimated time.

Happy Coding! #SayNoToNullReference

**Reference:**

- [https://www.youtube.com/watch?v=TJiLhRPgyq4](https://www.youtube.com/watch?v=TJiLhRPgyq4)
- [https://docs.microsoft.com/en-us/dotnet/csharp/nullable-references](https://docs.microsoft.com/en-us/dotnet/csharp/nullable-references)

The post [What’s with C# 8.0 – Nullable Reference Type](https://www.syncfusion.com/blogs/post/whats-with-c-8-0-nullable-reference-type.aspx) appeared first on [Syncfusion Blogs](https://www.syncfusion.com/blogs).