开发者

C# bool expression evaluation order [duplicate]

This question already has answers here: Closed 13 years ago.

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(A开发者_StackOverflow社区ccountIsInvalid || AccountIsUnregistered)

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


Personally, I never compare anything to false or true.

I would go with:

if (!somecondition) 

or:

if (somecondition)


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).


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.


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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜