4 methods to handle Nullable Reference in .NET

February 13 2023

Background


Understanding reference types and their nullable nature in C# programming is foundational. Reference types in C# have always been nullable, meaning that variables of any reference type can be assigned a value of null. In previous versions of C#, dereferencing a null variable was permitted without any checks.

In this article, we delve into the core aspects of handling nullable reference types in .NET, a crucial skill for modern C# programming.

The Nullable Reference Types feature was introduced in C# 8 to address this issue, and with the release of .NET 6, this feature is now enabled by default.

Example


Let's say we have a class:

Customer class

In .Net we will get a warning for underlined properties:

CS8618: Non-nullable field 'Name' must contain a non-null value when exiting constructor. Consider declaring the field as nullable.


How to handle?

Method #1


Steps
• Open .csproj project file
• Inside the PropertyGroup change Nullable to disable

Property group project options

Result: We won't get any more warnings for null references, but we can potentially run into a Null Reference Exception if we don't check objects for null before using them.


Method #2


Steps
• Make properties nullable reference type by using "?" .

Properties nullable references



Method #3


Steps
• Assign a default value to properties.

Properties with default value



Method #4


Steps
• Write a compiler directive #nullable to disable (or enable) feature.

Properties with compiler directive

If you have a .NET 6 project, open it now and try it.

If you haven't, make a coffee and check out these examples directly on my GitHub repository

Join 13,250+ subscribers to improve your .NET Knowledge.

There are 3 ways I can help you:

Design Patterns Simplified ebook

Go-to resource for understanding the core concepts of design patterns without the overwhelming complexity. In this concise and affordable ebook, I've distilled the essence of design patterns into an easy-to-digest format. It is a Beginner level. Check out it here.


Sponsorship

Promote yourself to 13,250+ subscribers by sponsoring this newsletter.


Join TheCodeMan.net Newsletter

Every Monday morning, I share 1 actionable tip on C#, .NET & Arcitecture topic, that you can use right away.


Subscribe to
TheCodeMan.net

Subscribe to the TheCodeMan.net and be among the 13,250+ subscribers gaining practical tips and resources to enhance your .NET expertise.