DCSIMG
C# anticelebrities – Part 1 – The ?? operator - David Birin's blog

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.

Published 19 January 2010 05:44 PM by DavidBi
תגים:,

Comments

# pd said on 19 January, 2010 08:14 PM

האם יש מקבילות ב VB?

# shachar said on 20 January, 2010 08:38 AM

כראש צוות פיתוח, אני תמיד חייב להחשב במתכנת ה"צעיר" ביותר.כולם יודעים שחוזק השרשרת הוא כחוזק החוליה החלשה ביותר, ולכן שימוש בכל מיני קיצורים כמו שהצגת )שהופכים את הקוד לפחות קריא) במיוחד עבור מתכנתים צעירים - הוא לא מומלץ!

קריאות הקוד שמשפיעה על תחזוקת הקוד היא החשובה.

Leave a Comment

(required) 
(required) 
(optional)
(required) 

Enter the numbers above: