Question

I'm trying to figure out what this code does in C# I'm not that familiar with the ? operator and this usage is confusing me. I know that if I do something like this.

Result = ans > 0 ? string.IsNullOrWhiteSpace(line[0]) : "";

It boils down to this:

if(ans > 0)
    Result = string.IsNullOrWhiteSpace(line[0]);
else 
    Result = "";

However I don't understand what happens when the line is like this instead:

Result = ans > 0 
       ? string.IsNullOrWhiteSpace(line[0]) 
       ? ""
       : line[0].Trim().ToUpper() 
       : "";

When it is written this way does it just pair the ? and with the first : it comes to? That doesn't really make sense because Result can only have one value. Hopefully this makes sense I tried to condense the code down to just the problem I am having so that it is easy to understand. Let me know if I'm not clear enough.

Was it helpful?

Solution

There is no ambiguity in parsing the expression of the form a ? b ? c : d : e: the only way to parse it is

a ? (b ? c : d) : e

A more interesting parse would be when a conditional expression is used as the last operand, not the middle. Microsoft documentation provides the answer to this:

The conditional operator is right-associative. The expression a ? b : c ? d : e is evaluated as a ? b : (c ? d : e), not as (a ? b : c) ? d : e.

However, it is a good idea to at least parenthesize expressions like that, because some readers of your code would need to consult a language reference in order to understand a potentially simple piece of logic.

OTHER TIPS

From your post,

Result = ans > 0 
   ? string.IsNullOrWhiteSpace(line[0]) 
   ? ""
   : line[0].Trim().ToUpper() 
   : "";

is equivalent to

if( ans > 0 )
{
    if( string.IsNullOrWhiteSpace(line[0]) )
    {
         Result = "";
    }
    else
    {
         Result = line[0].Trim().ToUpper();
    }
}
else
{
     Result = "";
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top