DEV Community

Cover image for C# 14 - Null Conditional Assignment in .NET10
Jp Lazaro
Jp Lazaro

Posted on

C# 14 - Null Conditional Assignment in .NET10

Most common error that developers encounter is NullException. A NullReferenceException is a runtime error in C# that occurs when we try to access a member (such as a method, property, or field) on a variable that is null as shown in the image below

In this blog you will know how C# 14 can help you to safely use your object properties and members without dealing with crashing and assure you will have a safe value assignment.

In C# 14 we can now use “?”

I have a small program that uses a Person class to get person information like name , age and gender. We will asign a null value to the Person john variable to show case the new feature of C# 14 Null Conditional Assignment.

OLD WAY
We use if / if else to check if the variable value is not null and use it for operation and we use it’s member for operation.

C# 14
we can now safely use value from any member of a variable without caring if it is null and having null checks everything we need to use them.

In the image below , I have changed few line of codes, as you noticed we are still getting the null exception

Let’s modify the code to add “?” beside the varaiable name observe the yellow mark in below image. the NullReferenceExceptionError gone already .

Since we are able to get the value of property without worrying about it’s nullability value we can set also a value to it without worrying about any error

I really love this update from .NET C# 14 it clearly expresses intent: update the object only if it exists, without adding extra control flow or risking a null-reference crash. It reduces boilerplate, keeps the code readable, and makes optional behavior explicit in a single line.

Top comments (1)

Collapse
 
pauljlucas profile image
Paul J. Lucas

C# is not C. This should not be tagged #c which is only for C.