DriLLFreAK100
DriLLFreAK100

Reputation: 1606

c# - conditional operator expression (a few in a row)

bool isGeneric = variableA != null ? variableB != null ? false : true : true;

I came across this line. Can anyone decipher this line/group them into parenthesis for me?

Upvotes: 5

Views: 145

Answers (1)

David L
David L

Reputation: 33815

It is a ternary inside of a ternary:

bool isGeneric = variableA != null 
    ? (variableB != null ? false : true) 
    : (true);

If variableA is not equal to null, check the first condition, else return true. In the first condition, return false if variableB is not null and return true if it is.

You could also translate it into the following if/else statements:

bool isGeneric = false;
if (variableA != null) 
{
    if (variableB != null)
        isGeneric = false;
    else 
        isGeneric = true;
}
else
    isGeneric = true;

Upvotes: 6

Related Questions