We have ?? Operator which is called null- coalescing operator in c#. It takes two operands, one at the left side and one at the right side and checks if the left side operand is null or not. If is is null then it will return the right side operand else it will return the left side operand.
Here is the simple example
using System;
namespace Null_Coalescing
{
class Program
{
static void Main(string[] args)
{
#region Null Assignment
string userId = null;//Assigning null value
Console.WriteLine( userId ?? "UserId is Null"));
#endregion
#region GUID assignment
userId = Guid.NewGuid().ToString();//Assigning GUID
Console.WriteLine(string.Format("UserId is {0}", userId ?? "Null"));
#endregion
Console.Read();
}
}
}
In this program, in first region we are assigning null to userId and using ?? operator inside Console.WriteLine method. Since userId is null at this time, it should return the right side operand which is "UserId is Null".
In second region we are assigning GUID to userId and using ?? operator inside Console.WriteLine method again. Since userId is has GUID as value at this time, it should return the left side operand which is the new GUID.
The Result will look like this:
UserId is null
1cd062ae-0216-4ad4-8d2d-2388e60ef1d5
0 Comment(s)