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... ?
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... ?
It's a "conditional operator" commonly known as the Ternary operator
It's found in many programming languages.
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.
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:
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!