Stand with Ukraine. Save peace in the world!

The founder of the project //devdigest, Andrey Gubskiy, launched a charity initiative to raise funds to support Ukraine.  Help ยป

How to Stop NullReferenceExceptions in .NET: Implementing Nullable Reference Types

August 10, 2021
 393
How to Stop NullReferenceExceptions in .NET: Implementing Nullable Reference Types
This article gives you a toolset for stopping NullReferenceExceptions in .NET code. The article centers around Nullable Reference Types (NRT), a feature that Microsoft added in C# 8. This article mentions five additional tools to ensure that users will never encounter the exception and explains how to implement them in your code. The Toolset Use non-nullable variables (Reference and value types): flag variables that should never be nullNull object pattern: inject default implementations with null behavior instead of null referencesTreat NRT warnings as errors: enforce the NRT rules to ensure that variables cannot enter a null/not-null state at the wrong time. Treat NRT warnings as errors so code will not compile if it breaks the NRT rules.Immutability: reduce the risk of NullReferenceException by only setting the reference onceArgumentNullException: An oldy but a goody. Stop code execution early in cases where the consuming code does not treat NRT warnings as errors.Unit testing: pass nulls into your code to make sure the appropriate result occurs. Mutation testing can help you achieve a higher level of certainty in your tests. Note: This article talks about libraries and consumers of those libraries. This might sound like it's about open-source libraries, and it is, but it's also about maintaining libraries in your team. If you publish libraries, someone will be consuming them, and that might even be you. Nullable Reference Types I recommend reading the official NRT documentation before or after reading this post. This article will refer to some terminology in that documentation which is important to understand. Reference types (classes, delegates, interfaces) are nullable by their nature. So, why is there suddenly a feature in the language that makes it sound as though they are suddenly nullable? The answer is partly historical. Value types (primary data types and structs) are not inherently nullable. C# added the nullable values types feature and added a nullable ? shortcut in C# 7. The NRT feature follows on from this. It extends the concept so that types suffixed with ? are meant to allow null. The corollary of this is that when we turn NRT on (nullable aware context), types without the? flip from being inherently nullable to not nullable. The syntax also brings C# in line with several other modern languages like Dart. When turned on, variables are in nullable aware context. You can turn nullable aware context on project by project or file by file. You need to turn it on file by file in the older csproj formats (pre SDK style). For example, you cannot turn it on at the project level for UWP or Android. Variables declared where nullable aware context is off are considered nullable oblivious.  If you leave this feature half-implemented, it could be confusing for people consuming the library. The IDE quick info bubbles may not identify between nullable aware and nullable oblivious variables. The consumer may not know if they allow null or not, and it's not easy for them to tell the difference between these and variables that are nullable oblivious. You might choose to convert entire projects for this reason or not to implement NRT on older projects.  Note: NRT support in IDEs is getting better, and IDEs will likely distinguish between nullable aware and nullable oblivious variables in the quick info in the future. Turn on NRT (Nullable Aware Context) There are a few different strategies for turning on NRT. I recommend doing it all at once and at the project level if you can. As mentioned, doing it for half a library could confuse the consumer. This is the Microsoft documentation on upgrading to NRT. Open up the csproj file and add these lines: <LangVersion>Latest</LangVersion> <Nullable>enable</Nullable> You will see lots of warnings. The existing variables where the reference type does not have a ? suffix will become not nullable. This flips the meaning of the existing code. Any reference type variables that were nullable change to not nullable. If you want to turn on nullable aware context at the file level, add this to the top of the file. #nullable enable Note: you can also leave the language version at 8. Turn on Treat Warnings as Errors Warnings are not enough. You need to treat warnings as errors. Warnings are too easy to ignore, so you need to tell the compiler to stop compilation when you violate an NRT constraint. If you don't, you won't get the most s...

Hot Vacancies

.NETBack End Developer

Field Complete
.NET

Field Complete is a team of passionate, young & fun-loving professionals looking to change the uneffective way that Servicing Industry works on US markets. Field Complete is growing really fast. We are looking for a Back End Developer to build a top-level modern API, ready for high load. Strong expertise with:

Senior Xamarin Developer

DraftKings
Mobile

You will join a mobile team which is working on two very exciting projects, Sportsbook and Casino. The apps are used by users in the US, where we are working on the regulated markets. We are releasing apps every two weeks. Our apps are generating almost 75% of the company revenue and the user base is growing daily. Technical stack on the project: Xamarin.Forms, MVVM with DI, NewRelic, Azure + App Center etc. Switching to .Net MAUI in the nearest 2-3 months.

Senior .NET Engineer

DraftKings
.NET

You will be working in a large US-oriented company that puts as a priority: security, performance, and stability. The candidate will work on pushing a huge number of changes (several thousand per sec) to several thousand clients in a near real-time manner.

Middle strong .NET developer

SoftServe
.NET

Our customer is an American company that develops software for businesses to help manage their networks, systems, and information technology infrastructure. The company provides purpose-built products for IT professionals, MSPs, and DevOps pros.

Junior .NET Developer

Chudovo OU
.NET

We are looking for a Junior .Net developer for being involved in to further development of the B2B platform for IT companies. You'll work on mostly back-end tasks closely with a Senior level developer.