Click here to Skip to main content
15,910,411 members
Please Sign up or sign in to vote.
2.33/5 (2 votes)
See more:
I was asked in interview:

What is the difference between:

C#
if(i == 2)
{
}


and

C#
if(2 == i)
{
}
Posted

It's a hold-over from C. In C, if you either use a bad compiler or don't have warnings turned up high enough, this will compile with no warning whatsoever (and is indeed legal code):

// Probably wrong
if (x = 2)
when you actually probably meant

if (x == 2)
You can work around this in C by doing:

if (2 == x)
A typo here will result in invalid code.

Now, in C# this is all piffle. Unless you're comparing two Boolean values (which is rare, IME) you can write the more readable code, as an "if" statement requires a Boolean expression to start with, and the type of "x=2" is Int32, not Boolean.

I suggest that if you see this in your colleagues' code, you educate them in the ways of modern languages, and suggest they write the more natural form in future.

In sort Both are same no difference between it.
 
Share this answer
 
v3
 
Share this answer
 
Comments
Adarsh chauhan 30-Aug-13 2:01am    
Good one.. my vote of 5
Thanks7872 30-Aug-13 2:02am    
Thanks Adarsh..:-)
Shambhoo kumar 30-Aug-13 2:06am    
great nice. my vote 5
Thanks7872 30-Aug-13 2:07am    
Thanks Shambhoo.. :-)
Shambhoo kumar 30-Aug-13 2:07am    
You most welcome.
It will give same result but first one indicate that variable is compared against constant value and second one indicate that constant is compared against variable
 
Share this answer
 
Yep they are same as far as C# is concerned. For more complex situations visit This Link

Thanks & Regard
Sham :)
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900