Different kind of if statement

Hi, I saw a unity video that showed a different way of using if statements:

int open = (day == holiday) ? 12:9;

I would like to know, Is this a new method? and does it have any performance benefits?

Thanks in advance.

  • Hakimo

it’s called a ternary operator, or often by programmers THE ternary operator. There are sometimes performance benefits in certain cases and compilers, but in general it’s just a compact and convenient (but potentially less readable) way of doing expression-based conditionals. Not sure if there’s any advantage in c#.

Interesting note, dunno about c#, but in C/C++, it can return an lvalue - meaning this is legal:

(a<b?a:b)=0; //sets whichever variable is smaller to 0

Use sparingly. Nobody but a fan of the IOCCC (International Obfuscated C Code Competition) will be impressed when they see something like “a>b?a>c?a:c:b>c?b:c” (returns max of a, b, and c) in your code. :slight_smile: