DCSIMG
January 2010 - Posts - David Birin's blog

January 2010 - Posts

C# anticelebrities – Part 1 – The ?? operator

I decided to start a new series of posts on the anticelebrities operators / keywords of C#,  being anticelebrity for a keyword / operator means that it’s not widely used by programmers. Some may say that main purpose of the members in the anticelebrity club is to be used in tricky interview questions, I hope that I will give them a push towards celebritness by explaining how to use them, at the worst case you will have some geek trivia questions for your next coffee break.

 

The ?? operator is a fairly simple one, it used as a shorten if condition when assigning a value into variables,  checking if the object being assigned into the variable points to a NULL reference, giving it a different value in case it is NULL, or the intended value if it isn’t NULL.

The following example will make things clearer:

static void Main(string[] args)
{
    string sampleText = null;
    string outputText;
 
    outputText = sampleText ?? "sampleText used to be null";
    /*
     * This is eqvivalent to one of the following:
     * 1:  if (outputText == null) 
        {
            outputText = "sampleText used to be null"; 
        }
        else 
        {
        outputText = sampleText
        }             
     * 2: outputText = sampleText == null ? "sampleText used to be null" : sampleText;            
    */
 
    Console.WriteLine(outputText);
 
    sampleText = "sampleText now has a value";
 
    outputText = sampleText ?? "sampleText used to be null";
 
    Console.WriteLine(outputText);
 
    Console.Read();
   
}

 

The output will be:


output

 

More anticelebrities coming soon… stay tuned.