-1
mainSize = mainSize < 0 ? 20 : mainSize ;
What do "?" and ":" mean within this assignment of the mainSize variable'?
-1
mainSize = mainSize < 0 ? 20 : mainSize ;
What do "?" and ":" mean within this assignment of the mainSize variable'?
1
This is the ternary operator (Docs).
It’s a shortened version with a slightly different behavior than if
.
Example of a conditional:
if (mainSize < 0)
mainSize = 20;
else
mainSize = mainSize;
Is equivalent to:
mainSize = (mainSize < 0) ? 20 : mainSize ;
To light difference between changing the if
by a ternary is that the ternary will result in one of the two values (as if it returned) while a if
will execute whatever is inside your execution block, not necessarily returning something.
Example, the if
hereafter cannot be represented as a ternary:
if (mainSize < 0)
negativo = true;
else
positivo = true;
0
mainSize = mainSize < 0 ? 20 : mainSize ;
? é igual ao if
if(mainSize < 0){
}
: igual ao else
else{
}
mainSize < 0 se 20 senão mainSize
Your answer, although correct, was very strange and confused due to bad formatting. I also suggest to do a better job in the newsroom.
Browser other questions tagged c#
You are not signed in. Login or sign up in order to post.
That’s a ternary operator: http://www.macoratti.net/14/11/c_tern1.htm
– Roberto de Campos
this is a ternary, it works as an if/Else
– Alvaro Alves
Other: https://answall.com/questions/4907/como-functioneste-if-else-com-e/322979#322979 and https://answall.com/questions/34200/dificuldade-na-syntax
– Barbetta
is the same as:
if (mainSize < 0) mainSize = 20 else mainSize = mainSize
– Ricardo Pontual
@Barbetta, I don’t believe these two are duplicates, one is
javascript
the otherc++
and this isc#
.– Roberto de Campos
@Robertodecampos, I flagged these questions because behavior is the same in all of them. I didn’t really think about the issue of different languages, I’ll see in Meta if there’s something talking about it.
– Barbetta
@Robertodecampos opened a question at the goal: https://pt.meta.stackoverflow.com/questions/7313/duplicate
– Barbetta
If the answers (existing and future potentials) answer the question, the closure as duplicate is valid.
– Bacco