C# Double Question Mark Operator - Null-Coalescing Operator C#
If you are reviewing a C# code and you've come across a double question mark operator (??), you must be wondering what this double question mark operator do in C#.
In this blog post, we will learn what this double question mark operator does and we will also see a few usages of this operator in some code examples.
Null Coalescing Operator C# - Double Question Mark Operator In C# (?? in C#)
The double question mark operator also called the null coalescing opertor in C#.
The null coalescing operator returns the value of its left-hand operand if it isn't null.
Otherwise, it evaluates the right-hand operand and returns its result.
Let's look at a practical code example and understand more about the Double Question Mark Operator or null coalescing operator.
string name = null; // some other code var checkName = name ?? "Name is null"; // Display Console.WriteLine(checkName);
Name is null
In the same code example, if the name field was not null, then checkName would have been evaluated to the value of the name field.
string name = null; // some other code name = "John Doe"; var checkName = name ?? "Name is null"; // Display Console.WriteLine(checkName);