From: ozbear on
On Wed, 23 Jun 2010 20:17:27 -0700, Peter Duniho
<NpOeStPeAdM(a)NnOwSlPiAnMk.com> wrote:

>Arne Vajh�j wrote:
>> On 23-06-2010 16:22, Burrows wrote:
>>> A new college at work use the following
>>>
>>> if(true==x)
>>> {
>>> ........
>>> }
>>>
>>> now I have through all my programming years and through various
>>> languages have always used
>>>
>>> if(x==true)
>>> {
>>> ........
>>> }
>>>
>>> Now yes we get the same result in checking for a true value but he's a
>>> smug sod so don't wish to question his methods. So should I tell him
>>> to change to my method or adopt his as it's better????
>>
>> You should use:
>>
>> if(x)
>> {
>> ...
>> }
>>
>> The reason behind the if(constant==variable) instead of the
>> more natural if(variable==constant) is to prevent writing
>> if(variable=constant) by accident.
>
>Note that doing so is not really an issue in C#, because types are not
>generally implicitly convertible to Boolean, and so an unintended
>assignment in an "if" statement will cause a compile-time error.
>
>The one obvious exception is of course some along the lines of "if (x =
>true)", but as stated by both Jeff and Arne, that's a silly thing to
>write in any case, whether you want = or ==.
>
<snip>

The other exception is if (x = y)
rather than just comparing to a constant, where x and y are both
Boolean. I got caught by this typo myself once where I really
wanted
if (x == y)

Oz
--
A: Because it fouls the order in which people normally read text.
Q: Why is top-posting such a bad thing?
A: Top-posting.
Q: What is the most annoying thing on usenet and in e-mail?
From: Peter Duniho on
ozbear wrote:
> The other exception is if (x = y)
> rather than just comparing to a constant, where x and y are both
> Boolean. [...]

That's not really an exception to the discussion here, because it
doesn't matter whether you put x or y first, there is still the risk of
accidental assignment. The idiom of putting the literal first doesn't
apply to that situation.

But yes, you do need to still be careful in that situation in C#.

Pete