I'm maintaining some code and have found the following pattern a lot:
var isMale = (row["Gender"].ToString() == "M") ? true : false;
instead of this:
var isMale = (row["Gender"].ToString() == "M");
Is there any reason why anyone would do this? Does anyone think the former is more readable or clearer? Is there some sort of old C "gotcha" that this is a hold-over from?
A valid reason? No.
It's usually produced by people who don't really understand that a condition is also in itself an expression, producing a boolean result. In particular, people schooled on a language where this isn't the case, such as many variants of BASIC.
I guess some people are not comfortable with assigning anything other that
true
orfalse
to a boolean variable. Don't know why this is, but I have observed it quite a few times.So, from that aspect it looks like:
set sarcasm on
but
and
set sarcasm off
Luckily Resharper makes short work of all these anti-patterns.
The 2nd way sure makes the most sense and I think it's easier to read.
The 2nd way is a bit more clever. I wouldn't put it past me to do something like you are finding if I was churning out code on a Friday afternoon and my brain was already gone for the weekend :-)
If you can't trust:
(row["Gender"].ToString() == "M")
to product true or false correctly, then you probably can't really trust:(row["Gender"].ToString() == "M") ? true : false;
either. To be sure, you undoubtedly need to repeat it at least a few more times:Then again, maybe you can't trust a combination of
==
and?:
by themselves either -- to be really sure, you probably need at least a bit more redundancy:Hmm...maybe I stayed up too late last night... :-)
The
"pattern" gets laughed at pretty much everywhere I've ever worked. No reason to do it in my opinion.
Definitely redundant. Could be a leftover practice from another programming language/environment that the original developer was retaining. I could also potentially see a developer viewing the first line as being more readable in that he/she can quickly see that it's setting a boolean when skimming through the code.