NEWAI for .NET Developers - skills, agents and practical lessonsExplore

4 methods to handle Nullable Reference in .NET

Stefan ĐokićFeb 13, 20232 min readCSharp

A quick word from me

This issue isn't sponsored - I write these deep dives in my free time and keep them free for everyone. If your company sells AI tools, dev tools, courses, or services that .NET developers would actually use, sponsoring an issue is the most direct way to reach them.

Want to reach thousands of .NET developers? Sponsor TheCodeMan →

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

Wrapping Up


Want to enforce clean code automatically? My Pragmatic .NET Code Rules course shows you how to set up analyzers, CI quality gates, and architecture tests - a production-ready system that keeps your codebase clean without manual reviews. Or grab the free Starter Kit to try it out.

Stefan Đokić
About the author

Stefan Đokić

Microsoft MVP and senior .NET engineer with extensive experience designing enterprise-grade systems and teaching architectural best practices.

Every Monday · Free

One practical .NET & architecture tip, every Monday.

Join 25,000+ engineers who improve their C# skills in a 5-minute read.

No spam. Unsubscribe anytime.