C# using “?” if else statements to set value whats this called

与世无争的帅哥 提交于 2019-12-12 11:17:14

问题


Hey I just came across the following statement

return name != null ? name : "NA";

I am just wondering what this is called in .NET

does the ? stand for i.e. then do this... ?


回答1:


It's a "conditional operator" commonly known as the Ternary operator

It's found in many programming languages.




回答2:


Just to add to everyone else's answers, note that in...

condition ? trueResult : falseResult

...only condition and either trueResult or falseResult (but not both) will be evaluated. That makes it possible to write code like this...

string name = user == null ? "<nobody>" : user.Name;

...without the risk of a NullReferenceException being thrown since user.Name will only be evaluated if user is non-null. Compare this behavior with VB.NET's If operator and IIf function.




回答3:


As Lion said in the comments, they are called ternary operators, though they are also known as inline if statmenets and conditional operator.

If you want to find out more about them, this Wikipedia page will help, and it has examples for many programming languages: http://en.wikipedia.org/wiki/%3F:




回答4:


This is the conditional operator which is a ternary operator. Since there are not so many other ternary operators (operator with three arguments) many people believe its called ternary operator, which is imprecise!



来源:https://stackoverflow.com/questions/9695493/c-sharp-using-if-else-statements-to-set-value-whats-this-called

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!