4 methods to handle Nullable Reference in .NET

4 methods to handle Nullable Reference in .NET

Read on the web directly: https://stefandjokic.tech/posts/4-methods-to-handle-nullable-reference?utm_source=Lnnullable

Background

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.

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:

In .Net we will get a warning for underlined properties:

In .Net we will get a warning for underlined properties:

CS8618: Non-nullable field 'Name' must contain a non-null value when exiting the constructor. Consider declaring the field as nullable.

How to handle it? Method #1

Steps:

• Open the .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.

Method #2

Steps

• Make properties nullable reference type by using "?" .

Method #3

Steps

• Assign a default value to properties

Method #4

Steps

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

If you have a (at least) .NET 6 project, open it now and try it.


Dream big!


Guido M.

Software Engineer |. NET Developer - Eskaa-IT

11mo

This is i.m.o. not quite correct. Setting <Nullable> to disabled makes reference types not nullable (unless you use the question mark to explicitly make it nullable). You will not get null reference exceptions because it is impossible for the object to be null. That is the whole intention of this new behaviour.

Like
Reply
Ali Shakkouf

Software Engineer, Backend Web Developer (Dot Net Core Developer)

1y

Useful info, thanks

Like
Reply
Murad Cafarov

CTO in Innovix Digital Solutions

1y

Public string name {get; set; } = default! This one also way to handle it :)

Diego Padilla

Passionate to build solutions

1y

This diferent methods are for diferent purposes right? For example with method 2 In case we are using code fist, wouldn't this create a migration with nullables?

Like
Reply

Thanks for sharing your knowledge with us!

Like
Reply

To view or add a comment, sign in

Insights from the community

Others also viewed

Explore topics