开发者

Coalesce operator - usage (c#) [closed]

开发者 https://www.devze.com 2023-02-19 17:29 出处:网络
It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical 开发者_如何学Pythonandcannot be reasonably answered in its current f
It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical 开发者_如何学Pythonand cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center. Closed 11 years ago.

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

0

精彩评论

暂无评论...
验证码 换一张
取 消