3

I have seen both

if(something == null)

and

if(null == something)

Does it make a difference in which order this null check happens? I do not see a difference in functionality but would love to know if there is reasoning behind it.

Joe
  • 6,401
  • 3
  • 28
  • 32

2 Answers2

7

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

Community
  • 1
  • 1
Jesse C. Slicer
  • 19,901
  • 3
  • 68
  • 87
  • I prefer this syntax, but I could see why people find it confusing. I just hate when I see this: if(true == myVariable) { } – Karl Anderson Jun 17 '13 at 00:42
5

Some programmers prefer to put the constant on the left side of an equality operator to avoid accidents (a typo of = instead of ==). In the second example, having the = typo would introduce a compiler error, which is easy to fix, whereas in the first example such a typo may introduce a bug that is very difficult to find.

This practice comes directly out of C and C++ programming style. I don't know whether it would affect C#. If it's no longer relevant, then it's more likely to be a habit rather than a strategy.

paddy
  • 60,864
  • 6
  • 61
  • 103