Today I was looking through some code, that I didn't write, and found an interesting nugget. For those of you who haven't figured out the title yet let me explain that first. In C# the ?: operator is pretty simple and handy. Lets look at this example:
cond-expr ? expr1 : expr2
If cond-expr evaluates to true then expr1 is returned, and if it evaluates to false then expr2 is returned. Simple enough right?
1: bool SomeValue = true;
2: string message = SomeValue ? "Yes" : "No";
3: // Message is "Yes"
4: message = !SomeValue ? "Yes" : "No";
5: // Message is "No"
The example I found was a little bit different, the example I found expr1 was true and expr2 was false.
1: bool IsSame = item1 == item2 ? true : false;
So basically if (item1 == item2) evaluates to true then IsSame is set to true and if false than IsSame is naturally set to false. This may seem to be fine at a glance, but it is the same as this:
1: bool IsSame;
2: if(item1 == item2)
3: {
4: IsSame = true;
5: }
6: else
7: {
8: IsSame = false;
9: }
There are really two problems with this, first its a good example of The Department of Redundancy Department. The second problem is that it confuses the intention of the line of code. If you have this:
1: bool IsSame = item1 == item2;
2:
3: // or in a slightly more explicit way
4: bool IsSame = (item1 == item2);
which is logically the same it is clear that you want IsSame to be true when item1 and item2 are are equal at first glance. I spent a little while trying to figure out why this is needed. The only reason you would need to use true and false as expr1 and expr2 is if bool had more than two values. I guess maybe its future proofing for maybe being added to the possible boolean values.