What’s New with C# 8.0 – Nullable Reference Type | Syncfusion Blogs
Live Chat Icon For mobile
Live Chat Icon
Popular Categories.NET  (174).NET Core  (29).NET MAUI  (207)Angular  (109)ASP.NET  (51)ASP.NET Core  (82)ASP.NET MVC  (89)Azure  (40)Black Friday Deal  (1)Blazor  (215)BoldSign  (14)DocIO  (24)Essential JS 2  (107)Essential Studio  (200)File Formats  (66)Flutter  (133)JavaScript  (221)Microsoft  (118)PDF  (81)Python  (1)React  (100)Streamlit  (1)Succinctly series  (131)Syncfusion  (914)TypeScript  (33)Uno Platform  (3)UWP  (4)Vue  (45)Webinar  (51)Windows Forms  (61)WinUI  (68)WPF  (159)Xamarin  (161)XlsIO  (36)Other CategoriesBarcode  (5)BI  (29)Bold BI  (8)Bold Reports  (2)Build conference  (8)Business intelligence  (55)Button  (4)C#  (147)Chart  (131)Cloud  (15)Company  (443)Dashboard  (8)Data Science  (3)Data Validation  (8)DataGrid  (63)Development  (628)Doc  (8)DockingManager  (1)eBook  (99)Enterprise  (22)Entity Framework  (5)Essential Tools  (14)Excel  (40)Extensions  (22)File Manager  (7)Gantt  (18)Gauge  (12)Git  (5)Grid  (31)HTML  (13)Installer  (2)Knockout  (2)Language  (1)LINQPad  (1)Linux  (2)M-Commerce  (1)Metro Studio  (11)Mobile  (507)Mobile MVC  (9)OLAP server  (1)Open source  (1)Orubase  (12)Partners  (21)PDF viewer  (43)Performance  (12)PHP  (2)PivotGrid  (4)Predictive Analytics  (6)Report Server  (3)Reporting  (10)Reporting / Back Office  (11)Rich Text Editor  (12)Road Map  (12)Scheduler  (52)Security  (3)SfDataGrid  (9)Silverlight  (21)Sneak Peek  (31)Solution Services  (4)Spreadsheet  (11)SQL  (10)Stock Chart  (1)Surface  (4)Tablets  (5)Theme  (12)Tips and Tricks  (112)UI  (387)Uncategorized  (68)Unix  (2)User interface  (68)Visual State Manager  (2)Visual Studio  (31)Visual Studio Code  (19)Web  (592)What's new  (332)Windows 8  (19)Windows App  (2)Windows Phone  (15)Windows Phone 7  (9)WinRT  (26)
What’s with C# 8.0 – Nullable reference type

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:

Comments (4)

Balasubramanian Sundararajan
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

Comments are closed.

Popular Now

Be the first to get updates

Subscribe RSS feed

Be the first to get updates

Subscribe RSS feed