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";
}
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.
It makes code shorter and more readable while providing the vitual functionality of checking on null objects.
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.
An Amazing situation where Coalesce Operator may be helpful. Thanks to Eric. Please follow the link and Eric's Answer
精彩评论