views:

285

answers:

4

Possible Duplicate:
== Operator and operands

Possible Duplicates:
Is there any difference between if(a==5) or if(5==a) in C#?
== Operator and operands

Ok, this may be stupid question, but searching in google (cant seem to ACTUALLY search for an exact phrase even with quotes)

What if any difference is there between

if(false == <somecondition>){

and

if(<somecondition> == false){

in C#? I am familiar with c#'s expression evalution, and understand how the order would make sense if you were doing something like:

if(AccountIsInvalid || AccountIsUnregistered)

I dont need a huge lesson, but would like to understand why some people prefer to do things with false==.... route.

+2  A: 

Personally, I never compare anything to false or true.

I would go with:

if (!somecondition)

or:

if (somecondition)
Patrick
+2  A: 

In C there would have been, perhaps, some reason to do this as you could easily make a mistake and use the assignment operator instead of the comparison operator, but in C# it shouldn't make any difference -- you'll get a compile warning if you use the assignment operator. If the assignment were a different type (say int), it would result in an error, since the result wouldn't be a legal expression for the if statement.

I would prefer it to be

if (!<somecondition>)
{
  ...
}

rather than a comparison to false (or true, for that matter).

tvanfosson
It is a warning, not an error: `bool b; if (b = true) { Console.WriteLine("abc"); }`
Marc Gravell
@Marc -- thanks for the clarification. That's is certainly true in the case of a bool variable. I hadn't considered that. I guess I'm just too used to seeing it in the context of some other value type -- which would be an error.
tvanfosson
Ah, fair enough ;-p Indeed, Cs tendency to treat anything non-zero as true is a pain.
Marc Gravell
A: 

This doesn't matter in C# like it does in c/c++ because conditions must evaluate to a boolean.

BioBuckyBall
Not *quite* true... they must have an implicit conversion to boolean, or a true function. Note also that the result of assignment is still bool, and works...
Marc Gravell
Consider: `bool b; if (b = true) { Console.WriteLine("abc"); }`
Marc Gravell
true enough, I should have said doesn't matter "as much as it does..." because you cant accidentally do the following in C#int i;if( i = 0 ) {...}
BioBuckyBall
+1  A: 

Before performing any optimizations or short-circuits, the compiler needs to resolve <somecondition> to true or false value, thus there is no reason why the compiler would evaluate the expressions <somecondition> == false and false == <somecondition> any differently.

This must surely be an issue of style, and style only.

Steve Guidi