locked
What does the ? mean in C#

    Question

  • I know this is saying role not equa TO an empty string and roleUp not sequal to an empty string but where does the question mark come in???? Any help on where I should go with this......

     



    (role !=
    string.Empty && roleUp != string.Empty ? ", " : "")

     

    Saturday, August 26, 2006 7:56 PM

Answers

  • The question mark is what is known as the ternary operator. It is a shorthand notation for

    If <condition> then <expression 1> else <expression 2>

    and has the form

    <condition> ? <expression 1> : <expression 2>

    and is usually used in conjuction with an assignment statement.

    Your statement will evaluate to a comma when both role and roleUp are not empty otherwise it will evaluate to an empty string (why not String.Empty again?). It looks like it might be used to separate role and roleUp by a comma when they both have values. If roleUp is a comma separated list of roles, then this statement decides when to add the comma.

    Saturday, August 26, 2006 10:55 PM

All replies

  • The operator is called a "ternary" (mean "three operands").  It takes the form

    expressionA ? expression B  : expressionC

    If expressionA is true, the whole thing is equal to expressionB.  If it's false, it equals expressionC

     

    Saturday, August 26, 2006 10:47 PM
  • The question mark is what is known as the ternary operator. It is a shorthand notation for

    If <condition> then <expression 1> else <expression 2>

    and has the form

    <condition> ? <expression 1> : <expression 2>

    and is usually used in conjuction with an assignment statement.

    Your statement will evaluate to a comma when both role and roleUp are not empty otherwise it will evaluate to an empty string (why not String.Empty again?). It looks like it might be used to separate role and roleUp by a comma when they both have values. If roleUp is a comma separated list of roles, then this statement decides when to add the comma.

    Saturday, August 26, 2006 10:55 PM
  • Does the statement in your post really work ? I guess the second expression evaluates to a string value which results in an error as the conditional operators take bool values.Are you missing any paranthesis here?

    Sunday, August 27, 2006 4:07 AM
  • No, its actually a statement in a bigger expression i just pasted one line of code.....
    Sunday, August 27, 2006 5:14 AM
  • Yes, it would work, as && has a slightly higher precedence than :?, so it would be intrepreted as:

     ((role != string.Empty && roleUp != string.Empty)  ?  ", "  :  "")

    But, I agree it should have been written like that, not for the compiler, but for the humans who would be reading it.


     

    Tuesday, August 29, 2006 5:58 PM