What does each sign mean in this assignment in C #? [duplicate]

-1
 mainSize = mainSize < 0 ? 20 : mainSize ;

What do the "?" and the ":" within that assignment of the 'mainSize' variable?

    
asked by anonymous 14.09.2018 / 22:23

2 answers

1

This is the ternary operator ( docs ).

This is a shortened version with slightly different behavior than if .

Example of a conditional:

if (mainSize < 0)
    mainSize = 20;
else
    mainSize = mainSize;

It is equivalent to:

mainSize = (mainSize < 0) ? 20 : mainSize ;
The light difference between changing the if by a ternary is that the ternary will result in one of the two values (as if it returns) while a if will execute whatever is inside of your execution block, not necessarily returning something.

For example, the% w /% of the following can not be represented as a ternary:

if (mainSize < 0)
    negativo = true;
else
    positivo = true;
    
14.09.2018 / 22:32
0
mainSize = mainSize < 0 ? 20 : mainSize ;

? é igual ao if

if(mainSize < 0){
}

: igual ao else
else{

}

mainSize < 0 se 20 senão mainSize
    
14.09.2018 / 22:31