Home > DeveloperSection > Forums > How to use Null Coalescing Operator (?) in C#
Anupam Mishra

Total Post:135

Points:949
Posted on    January-24-2016 10:43 PM

 C# C#  .NET 
Ratings:


 1 Reply(s)
 237  View(s)
Rate this:
Hi Everyone..
I want to use Null Coalescing Operator (?) in my program. Please give me a better solution


Shiva Shukla
Shiva Shukla

Total Post:13

Points:91
Posted on    January-24-2016 11:12 PM

The ?? operator is also known as the null-coalescing operator. It returns the left side operand if the operand is not null else it returns the right side operand.
  1. int? x = null;  
  2. int y = x ?? 99;  
  3. Console.WriteLine("The Value of 'Y' is:" + y);  
  4. string message = "Operator Test";  
  5. string resultMessage = message ?? "Original message is null";  
  6. Console.WriteLine("The value of result message is:" + resultMessage);  

In the preceding example, we have an integer variable "x" that is a nullable type and has a null value so in the result variable "Y" the return value is 99. The same is in the second example. We could check whether the message was null and return an alternate value and result message return "Operator test because message variable has value.

Don't want to miss updates? Please click the below button!

Follow MindStick