Just I would like to know, is there any difference between
if (a==5) or if (5==a)
in C#, Which one is better?
Just I would like to know, is there any difference between
if (a==5) or if (5==a)
in C#, Which one is better?
There's no difference - assuming that "a" is an integer.
I know some people prefer if (5==a)
because in c & c++ if you wrote if (5=a)
by mistake you'd get a compiler error while if (a=5)
would result in a bug.
C# raises a compiler error in the latter case, so it's not an issue.
I'd actually say there is a difference, but it's not a technical one (as everyone has well covered already) - readability. It matters and the first form is much more natural.
The if(5 == a)
construct is common in C/C++ because boolean values are represented using ints. Thus if you write a = 5
by mistake this can be evaluated in the context of the if
, which is most likely not what you wanted.
In C# there's no implicit conversion from int
to bool
, so if you type =
instead of ==
you'll get a compile error.
no difference, it is an old habit to avoid if(a=5) in c/c++.
These questions/answers are about the same:
Both are equivalent. I remember when I used to code in C, I preferred 'if (5==a)' because it guarantees that I haven't typed 5=a accidentally as the compiler would throw error. This would not happen if we write 'if (a=5)'. Though it is a typo, it would not generate any compiler error and would go unnoticed.
But, in C# it is not the case. There is no logical reason to write 'if (5==a)'. If we had written 'if(a=5)', the compiler would throw an error. So in C# use 'if(a==5)'!
With correct design, there is no difference between "a == 5" and "5 == a". But there is some special situation, where has "a == 5" and "5 == a" different behaviour. It's very unpropably, but it is posible.
Nevertheless this example is constructed for demonstration of the situation, and I does not recomend do thinks such this.
Example:
public class BadClass {
public int Value;
public static implicit operator int( BadClass c ) {
return c.Value;
}
//public static implicit operator BadClass( int n ) {
// return new BadClass { Value = n };
//}
public static bool operator ==( BadClass c, int n ) {
return (c.Value + 1 == n);
}
public static bool operator !=( BadClass c, int n ) {
return (c.Value + 1 != n);
}
public override bool Equals( object obj ) {
if ( obj is int ) {
return (this == (int)obj);
}
else {
return base.Equals( obj );
}
}
public override int GetHashCode() {
return base.GetHashCode();
}
}
...
BadClass a = new BadClass { Value = 13 };
var rslt_1 = (13 == a); //there will be true
var rslt_2 = (a == 13); //there will be false
Other than the safety if (5==a)
gives you, No.
Only difference is if you forget the second equals, the first version is still a valid statement whereas the second version will raise a compile time error.
HTH
cheers,