The ?? operator is called the null-coalescing operator. You can use it to provide a default value for nullable value types or for reference types. The operator returns the left value if it’s not null; otherwise, the right operand. Here is an example of using the operator.
int? x = null; int y = x ?? -1;
In this case, the value of y is -1 because x is null. You can also nest the null-coalescing operator, below is an example,
int? x = null;
int? z = null;
int y = x ??
z ??
-1;
Of course, you can achieve the same with an if statement but the null-coalescing operator can shorten your code and improve its readability.
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.
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace ConsoleApplication1 { classProgram { staticint? GetNullableInt() { returnnull; } staticstring GetStringValue() { return"Mindstick Softwares"; } staticvoid Main() { int? x = null; // Set y to the value of x if x is NOT null; otherwise, // if x = null, set y to 5. int y = x ?? 5; // Assign i to return value of the method if the method's result // is NOT null; otherwise, if the result is null, set i to the // default value of int. int i = GetNullableInt() ?? default(int); string m = GetStringValue(); // Display the value of s if s is NOT null; otherwise, // display the string "Unspecified". Console.WriteLine(m?? "Unspecified"); Console.WriteLine(i); Console.ReadKey(); } } }
Liked By
Write Answer
How to use null-coalescing operator?
Join MindStick Community
You have need login or register for voting of answers or question.
Shadman Kudchikar
19-Jun-2019The ?? operator is called the null-coalescing operator. You can use it to provide a default value for nullable value types or for reference types. The operator returns the left value if it’s not null; otherwise, the right operand. Here is an example of using the operator.
In this case, the value of y is -1 because x is null. You can also nest the null-coalescing operator, below is an example,
Of course, you can achieve the same with an if statement but the null-coalescing operator can shorten your code and improve its readability.
You can learn more about Null Coalescing Operator C# here.
Sushant Mishra
06-Jul-2017The ?? 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.