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


if ("" != customer.Name) 
  // some code

2 Answers 2


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

  • 1
    The compiler will not warn you (I believe C compilers do that), it will error out.
    – svick
    Feb 26, 2013 at 0:22
  • @svick: thanks, you are absolutely correct. Just confirmed it. Feb 26, 2013 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/… Feb 26, 2013 at 8:28

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.

  • 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. Feb 25, 2013 at 23:23

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