Join the social network of Tech Nerds, increase skill rank, get work, manage projects...
 
  • Using Null-coalescing operator (??) in C#

    • 0
    • 4
    • 1
    • 1
    • 0
    • 0
    • 0
    • 0
    • 183
    Comment on it

    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)

Sign In
                           OR                           
                           OR                           
Register

Sign up using

                           OR                           
Forgot Password
Fill out the form below and instructions to reset your password will be emailed to you:
Reset Password
Fill out the form below and reset your password: