In this post, we will be learning about the null coalescing operator in C# with help of an example code snippet.
Topics Covered
Introduction
The ??
operator is called the null coalescing operator. It returns the left-hand operand if the operand is not null otherwise, it returns the right-hand operand.
You might already know that C# 2.0 provides us Nullable Types that can be used to store null values for value type variables such as int, float, decimal, etc.
For example, let’s consider the following code snippet.
int? x = null; int y = x ?? 0; Console.WriteLine(y);
In the above example, x is a nullable int and if you assign it to the non-nullable int y then it will throw a runtime exception if x is null.
Purpose of ?? Null Coalescing Operator in C#
Well, ??
provides a convenient way to assign a nullable type to a non-nullable type.
int y = x ?? 0;
It saves us having to write code that tests for null and sets a value appropriately. The above statement sets the value of y to the value of x unless the value in x is null, in which case it sets it to 0.
if (x == null) y = 0; else y = x;
In other words ?? is a short form of the above test.
The result of a ?? operator is not considered to be constant even if both its arguments are constants.
Null Coalescing Operator in C#
If you kind of not feeling to read the post, you may watch this youtube video.
C# Mastery Course
One of the best courses to master your C# skills right from level zero. This series is divided into 4 sections:
- C# Basics
- C# Intermediate
- C# Advanced
- Unit Testing for C# Developers
Hopefully, this post was useful for you. Please share it with your friends or colleagues.
To read more on ?? operator you may refer 👉 ?? Operator in C#
Happy Coding!
Disclaimer: Most of the content is FREE. But some resources may contain affiliate links. When you purchase, I may receive a commission from the seller, at no extra cost to yourself.