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

前端 未结 7 1962
别那么骄傲
别那么骄傲 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:24

    The ?? operator (also known as the null-coalescing operator) is less known than the ternary operator, as it made its debut with .NET 2.0 and Nullable Types. Reasons for not using it probably include not begin aware that it exists, or being more familiar with the ternary operator.

    That said, checking for null is not the only thing the ternary operator is good for, so it's not a replacement for it as such, more like a better alternative for a very specific need. :)

提交回复
热议问题