So I was writing an inline if statement the other day… you know the ones –
booleanStatement ? resultIfTrue : resultIfFalse;
It was pretty simple, so I didn’t think too much about it until I ran some unit tests….
Here’s what my code kind of looked like:
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public int GetIndex(int group, string badge) | |
{ | |
return (group - 1) * 2 + badge == "Gold" ? 0 : 1; | |
} |
So, what would you expect the result to be given these scenarios:
Group | Badge | Result ? |
1 | “Gold” | ? |
1 | “Silver” | ? |
2 | “Gold” | ? |
2 | “Silver” | ? |
3 | “Gold” | ? |
3 | “Silver” | ? |
The answer might surprise you:
Group | Badge | Result ? |
1 | “Gold” | 1 |
1 | “Silver” | 1 |
2 | “Gold” | 1 |
2 | “Silver” | 1 |
3 | “Gold” | 1 |
3 | “Silver” | 1 |
Uh… what?
Yeah, so it turns out if you don’t put parenthesis around your inline if (when you’re trying to do math on the result), it will evaluate the entire expression on the left hand side of the ==. It seems pretty obvious to me now… but for some reason I was just assuming that C# wouldn’t evaluate a complex statement on the left side. I’ll just leave this as a cautionary tale.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public int GetIndex(int group, string badge) | |
{ | |
return (group - 1) * 2 + (badge == "Gold" ? 0 : 1); | |
} |
Group | Badge | Result ? |
1 | “Gold” | 0 |
1 | “Silver” | 1 |
2 | “Gold” | 2 |
2 | “Silver” | 3 |
3 | “Gold” | 4 |
3 | “Silver” | 5 |