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:
August 10, 2021
599
479