Coalesce operator - usage (c#) [closed]

2019-07-13 11:33发布

问题:

Ive seen an increasing number of pieces of code that use the coalesce operator in a (to me anyway) slightly odd manner, thoughts on this usage?

e.g. doing:

string foo = null;
void bar(){
 foo = foo??"hello";
}

instead of

string foo = null;
void bar(){
 if (foo==null)
  foo="hello";
}

回答1:

That looks like an entirely reasonable use of the null coalescing operator to me. Note that it's not quite the same as the first code snippet, as it will be reassigning foo either way. This could be significant if you were actually using a property rather than a variable - the property setter would be invoked regardless of the current value.



回答2:

It makes code shorter and more readable while providing the vitual functionality of checking on null objects.



回答3:

The main differentiating factor is that ?? is an operator and can therefore be used in other expressions. As to where to use it -- it's completely up to developer.



回答4:

An Amazing situation where Coalesce Operator may be helpful. Thanks to Eric. Please follow the link and Eric's Answer



标签: c# coalesce