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:
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.
Software Engineer |. NET Developer - Eskaa-IT
11moThis 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.
Software Engineer, Backend Web Developer (Dot Net Core Developer)
1yUseful info, thanks
CTO in Innovix Digital Solutions
1yPublic string name {get; set; } = default! This one also way to handle it :)
Passionate to build solutions
1yThis 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?
--
1yThanks for sharing your knowledge with us!