DEV Community

Ishaan Sheikh
Ishaan Sheikh

Posted on β€’ Edited on

2 1

Null Coalescing Operator in C#

If you have used javascript before you probably have used the logical OR (||) operator while assigning values to a variable. For example,

let a = b || c;
Enter fullscreen mode Exit fullscreen mode

The above code snippet assigns the value of b to a if it is defined, else assign c to it.

In C# the ?? operator is used to handle this kind of situations.
This operator us available in C# 8.0 and later.

Syntax

a = b ?? c;
Enter fullscreen mode Exit fullscreen mode

The above statement will be equivalent to

if(b == null)
{
   a = c
}
else
{
    a = b
}
Enter fullscreen mode Exit fullscreen mode

Examples

Below are some use-cases for ?? operator.

1. Throwing an exception

int? val = input ?? throw new Exception("'input' cannot be null");
Enter fullscreen mode Exit fullscreen mode

2. Assigning a default value

int? requiredValue = userInput ?? -1;
Enter fullscreen mode Exit fullscreen mode

3. This operator can also be Nested

int? a = 1;
int? b = null;
int? c = 3;

int? d = a ?? b ?? c;

Console.Write(d); // 1
Enter fullscreen mode Exit fullscreen mode

This operator is right-associative, so the above example will evaluated as

a ?? (b ?? c)
a ?? (null ?? 3)
a ?? 3
1 ?? 3
1
Enter fullscreen mode Exit fullscreen mode

Hostinger image

Get n8n VPS hosting 3x cheaper than a cloud solution

Get fast, easy, secure n8n VPS hosting from $4.99/mo at Hostinger. Automate any workflow using a pre-installed n8n application and no-code customization.

Start now

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs

πŸ‘‹ Kindness is contagious

Engage with a wealth of insights in this thoughtful article, valued within the supportive DEV Community. Coders of every background are welcome to join in and add to our collective wisdom.

A sincere "thank you" often brightens someone’s day. Share your gratitude in the comments below!

On DEV, the act of sharing knowledge eases our journey and fortifies our community ties. Found value in this? A quick thank you to the author can make a significant impact.

Okay