Is there a difference between if (a == 5) or if (5 == a) in C #?

I just wanted to know if there is a difference between

if (a == 5) or if (5 == a)

in C #, which one is better?

+3
source share
8 answers

There is no difference - considering that "a" is an integer.

I know that some people prefer if (5==a) , because in c and C ++, if you wrote if (5=a) by mistake, you will get a compiler error, and if (a=5) will lead to an error.

C # causes a compiler error in the latter case, so this is not a problem.

+18
source

I would say that there is a difference, but this is not technical (since everyone is already well covered) - readability . This is important, and the first form is much more natural.

+8
source

The if(5 == a) construct is common in C / C ++ because booleans are represented using ints. Thus, if you write a = 5 by mistake, this can be evaluated in the context of if , which is most likely not what you wanted.

There is no implicit conversion from int to bool in C #, so if you type = instead of == , you will get a compilation error.

+6
source

Both are equivalent. I remember when I used the code in C, I preferred "if (5 == a)" because it guarantees that I did not type 5 = by accident, since the compiler executed the error. This will not happen if we write 'if (a = 5)'. Although this is a typo, it will not generate compiler errors and will go unnoticed.

But in C # this is not the case. There is no logical reason to write "if (5 == a)". If we wrote "if (a = 5)", the compiler would throw an error. So in C # use 'if (a == 5)'!

+3
source

With the right design, there is no difference between "a == 5" and "5 == a". But there is a special situation where there is "a == 5" and "5 == a" other behavior. It is very difficult, but it is possible.

However, this example is built to demonstrate the situation, but I do not recommend it . He thinks so.

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 
+1
source

In addition to security if (5==a) , you can specify No.

0
source

The only difference is that if you forget the second equal, the first version is still valid, while the second version will cause a compile-time error.

NTN

amuses

0
source

All Articles