Take the 2-minute tour ×
Programmers Stack Exchange is a question and answer site for professional programmers interested in conceptual questions about software development. It's 100% free, no registration required.

This question already has an answer here:

I came across below style of writing if statements in C#, on msdn code examples. Usually when I write if statements, the conditions I would write `(Customer != null)

I want to know if there is any difference/gain in writing statement like below:

Customer customer;
if (null != customer)
{
  // some code
}

Or

if ("" != customer.Name) 
{
  // some code
}
share|improve this question

marked as duplicate by Greg Hewgill, MichaelT, Martijn Pieters, Eric King, gnat Feb 26 '13 at 5:03

This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.

add comment

2 Answers

up vote 4 down vote accepted

This is legal in C# and is colloquially known as a Yoda Condition. Many people in the C/C++ world like this because it guards at compile time against replacing == with = by accident. However, it has fallen out of favor in C# due to the fact the compiler will flag it (the single =) as an error in that instance (so long as it's not a boolean eval).

share|improve this answer
1  
The compiler will not warn you (I believe C compilers do that), it will error out. –  svick Feb 26 '13 at 0:22
    
@svick: thanks, you are absolutely correct. Just confirmed it. –  Jesse C. Slicer Feb 26 '13 at 1:20
    
I disagree with most/many. As that is totally subjective. It may be true from your perspective. But from my perspective (totally different to your): Many people in the C++ think this is a terrible idea. programmers.stackexchange.com/questions/162256/… –  Loki Astari Feb 26 '13 at 8:28
add comment

I'm not sure in C#, but in C++ it's legal to assign value inside a if statement.

Writing the if this way prevent you from bad surprises if one forgets one character: something like if ( customer.Age = 15).

When inversing rhs and lhs it's not possible to assign customer.Age to the value 15 which is const.

So, probably the code you're reading was written by a former C++ folk.

But as MS Visual has warning for assignment inside ifs, I tend to never to write them this way.

share|improve this answer
2  
In C# it is legal to have an assignment in the condition of an if statement only if the compile-time type of the assignment is (1) bool, or (2) a type which implements operator true. So bool b = false; if (b = M()) { ... } would be legal, but int i = 0; if (i = M()) { ... } would be illegal. –  Eric Lippert Feb 25 '13 at 23:23
add comment

Not the answer you're looking for? Browse other questions tagged or ask your own question.