February 13 2023
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.
Let's say we have a 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.
Steps • Open .csproj project file • Inside the PropertyGroup change Nullable to disable

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.
Steps • Make properties nullable reference type by using "?" .

Steps • Assign a default value to properties.

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

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
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.
Stop arguing about code style. In this course you get a production-proven setup with analyzers, CI quality gates, and architecture tests — the exact system I use in real projects. Join here.
Not sure yet? Grab the free Starter Kit — a drop-in setup with the essentials from Module 01.
Design Patterns that Deliver — Solve real problems with 5 battle-tested patterns (Builder, Decorator, Strategy, Adapter, Mediator) using practical, real-world examples. Trusted by 650+ developers.
Just getting started? Design Patterns Simplified covers 10 essential patterns in a beginner-friendly, 30-page guide for just $9.95.
Every Monday morning, I share 1 actionable tip on C#, .NET & Architecture that you can use right away. Join here.
Join 20,000+ subscribers who mass-improve their .NET skills with actionable tips on C#, Architecture & Best Practices.
Subscribe to the TheCodeMan.net and be among the 20,000+ subscribers gaining practical tips and resources to enhance your .NET expertise.