why do we prefer ? to ?? operator in c#?

前端 未结 7 1947
别那么骄傲
别那么骄傲 2020-12-13 09:05

I recently found that we can use ?? operator to check nulls. Please check the below code samples:

   var res = data ?? new data();

This is

7条回答
  •  北海茫月
    2020-12-13 09:36

    One reason (as others have already touched) is likely to be lack of awareness. It could also be (as in my own case), a wish to keep the number of approaches to do similar things in a code base down as much as possible. So I tend to use the ternary operator for all compact if-a-condition-is-met-do-this-otherwise-do-that situations.

    For instance, I find the following two statements rather similar on a conceptual level:

    return a == null ? string.Empty : a;    
    return a > 0 ? a : 0;
    

提交回复
热议问题