Coffeehouse Post

Single Post Permalink

View Thread: C# trivia question
  • Proton2

    I have never heard of this operator... and now I have Smiley

    From:

    http://stackoverflow.com/questions/446835/what-do-two-question-marks-together-mean-in-c

     

    It's the null coalescing operator, and quite like the ternary (immediate-if) operator.

    FormsAuth = formsAuth ?? new FormsAuthenticationWrapper();

     

    expands to:

    FormsAuth = formsAuth != null ? formsAuth : new FormsAuthenticationWrapper();

     

    which further expands to:

    if(formsAuth != null)

        FormsAuth = formsAuth;

    else

        FormsAuth = new FormsAuthenticationWrapper();

     

    In English, it means "If whatever is to the left is not null, use that, otherwise use what's to the right."

    Note that you can use any number of these in sequence. The following statement will assign the first non-null Answer# to Answer:

    string Answer = Answer1 ?? Answer2 ?? Answer3 ?? Answer4;