How to use Null Coalescing Operator (?) in C#

Total Post:135

Points:949
C#  .NET 
C#
 680  View(s)
Ratings:
Rate this:
Hi Everyone..
I want to use Null Coalescing Operator (?) in my program. Please give me a better solution
  1. Post:13

    Points:91
    Re: How to use Null Coalescing Operator (?) in C#

    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.

Answer

NEWSLETTER

Enter your email address here always to be updated. We promise not to spam!