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