C# 8.0 Nullable Reference Types
Muhammad Mazhar
Senior Software Engineer | ASP.NET | .NET Core | Entity Framework | Azure DevOps | Full-Stack Developer | Expert @ CDOXS Private Limited | AI | Machine learning Enthusiast
C# 8.0 brings a significant enhancement to the language that aims to minimize the dreaded NullReferenceException. Enter Nullable Reference Types (NRTs), a feature that allows developers to express whether a reference type is expected to be null or not, right in the type system.
What are Nullable Reference Types?
NRTs provide a way to explicitly declare the nullability of reference types. By default, reference types in C# 8.0 are non-nullable, and you can make them nullable by adding a suffix "?".
Why Use Nullable Reference Types?
How to Enable Nullable Reference Types?
To enable NRTs, you can add #nullable enable at the top of your C# files or configure your project file with <Nullable>enable</Nullable>.
领英推荐
C#
#nullable enable
public class Book
{
public string Title { get; set; }
public string? Author { get; set; } // Author can be null
}
This C# snippet demonstrates how to declare a class with NRTs, indicating that Title must not be null, while Author can be null.
Embracing the Change:
While adopting NRTs may require some adjustments to existing codebases, the benefits in terms of code robustness and maintainability are well worth it. It’s a step towards making nulls a thing of the past!
Dive into the world of C# 8.0 and embrace Nullable Reference Types to write safer, clearer, and more reliable code. Say goodbye to null-induced headaches and hello to a new era of C# development!