What do two question marks together mean in C#?

前端 未结 18 1424
借酒劲吻你
借酒劲吻你 2020-11-22 03:41

Ran across this line of code:

FormsAuth = formsAuth ?? new FormsAuthenticationWrapper();

What do the two question marks mean, is it some ki

18条回答
  •  傲寒
    傲寒 (楼主)
    2020-11-22 04:17

    As correctly pointed in numerous answers that is the "null coalescing operator" (??), speaking of which you might also want to check out its cousin the "Null-conditional Operator" (?. or ?[) that is an operator that many times it is used in conjunction with ??

    Null-conditional Operator

    Used to test for null before performing a member access (?.) or index (?[) operation. These operators help you write less code to handle null checks, especially for descending into data structures.

    For example:

    // if 'customers' or 'Order' property or 'Price' property  is null,
    // dollarAmount will be 0 
    // otherwise dollarAmount will be equal to 'customers.Order.Price'
    
    int dollarAmount = customers?.Order?.Price ?? 0; 
    

    the old way without ?. and ?? of doing this is

    int dollarAmount = customers != null 
                       && customers.Order!=null
                       && customers.Order.Price!=null 
                        ? customers.Order.Price : 0; 
    

    which is more verbose and cumbersome.

提交回复
热议问题