What does each signal mean in this assignment in C#?

Asked

Viewed 83 times

-1

 mainSize = mainSize < 0 ? 20 : mainSize ;

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

  • That’s a ternary operator: http://www.macoratti.net/14/11/c_tern1.htm

  • this is a ternary, it works as an if/Else

  • Other: https://answall.com/questions/4907/como-functioneste-if-else-com-e/322979#322979 and https://answall.com/questions/34200/dificuldade-na-syntax

  • is the same as: if (mainSize < 0) mainSize = 20 else mainSize = mainSize

  • @Barbetta, I don’t believe these two are duplicates, one is javascript the other c++ and this is c#.

  • @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.

  • @Robertodecampos opened a question at the goal: https://pt.meta.stackoverflow.com/questions/7313/duplicate

  • 2

    If the answers (existing and future potentials) answer the question, the closure as duplicate is valid.

Show 3 more comments

2 answers

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

You are not signed in. Login or sign up in order to post.