简体   繁体   中英

C# multiple sequence ? conditional operator

I got an exam and saw a question like;

var b = (1==2) ? (1==1) ? (2==1) ? "A" : "B" : "C" : "D";

What is the b and how it works a condition like this?

Thanks.

A ternary operator acts as such:
The statement

variable = condition ? value1 : value2

is equivalent to

if (condition) 
{
  variable = value1;
} 
else 
{
  variable = value2;
}

So in your case,

var b = (1==2) ? (1==1) ? (2==1) ? "A" : "B" : "C" : "D";

is simply a few nested ternary operators, and is the same as

    var b; 
    if (1==2)
    {
      if (1==1) 
      {
        if (2==1) 
        {
          b = "A";
        }
        else 
        {
         b = "B";
        }
      }
      else 
      {
        b = "C";
      }
    }
    else
    {
      b = "D";
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM