3

I was always taught to put the variable you are checking to the Left side example

if (myvariable == null)

whilst technically not incorrect to do

if (null == myvariable)

is there any programmatic reason you would do this?

fubo
  • 44,811
  • 17
  • 103
  • 137
Noreen
  • 159
  • 1
  • 12
  • 2
    I don't think there is a technical reason to not do this. I just don't do it or like it because it seems backwards. – user1666620 May 04 '16 at 14:53
  • 1
    [Yoda conditions](https://en.wikipedia.org/wiki/Yoda_conditions) – p.s.w.g May 04 '16 at 14:55
  • This was a very nice explanation for it within C# and C++ contexts. https://www.reddit.com/r/learnprogramming/comments/4hsejw/explain_the_difference_between_5_value_versus/d2rx5qf – AntiTcb May 04 '16 at 14:56
  • 1
    As @user1666620 mentioned, it is a preference. However, it is nearly a universal convention to use `if (myvariable == null)`. Doing it the other way around will make the code less readable for the vast majority of programmers. Write code for humans, not machines. – Lews Therin May 04 '16 at 14:58
  • Usually, it's a carryover from languages where it's easy to write code where you can accidentally assign null to a variable and still have compilable code. For those languages the result would always evaluate to `false` while you have the unintended consequence of clearing a variable. The C# compiler will catch this issue so the code won't compile. However, there are many languages where you can fall prey to that issue. Comparing against null first will generate a compiler error since you can't reassign `null`'s value. – Berin Loritsch May 04 '16 at 15:38

2 Answers2

0

suppose you forget == and write =. In this case x=5 will be compiled but 5=x not.

benchpresser
  • 2,171
  • 2
  • 23
  • 41
  • `if (myvariable = null)` will not compile. This is only a problem if the value is a `bool` e.g. `if (x = true)` although in that case you would simply write `if (x)`. – Lee May 04 '16 at 14:57
-2

My first boss used to insist on putting null on the left hand side. His argument was that some day you will leave out an = and save yourself possibly lots of time debugging, since you can't assign to null so it will throw an error.

Consider the following c#

var y = false;
var x = y = true;
// y = true, x = true.

and

var y = false;
var x = y == true;
// x = false, y = false

These both end up with different y and x values, but it would be easy to type one when you meant the other. However, if you have the habit of putting your constant values on the left hand side of the operator, then you will get compiler errors instead.

var x = true = y; // won't compile
var x = true == y; // will compile

Also, if you write in vb and c# a lot, vb only has 1 equal for comparison, so it definitely can be a good idea if you're coding in both languages, as you may copy and paste some code and suddenly what was a comparison is now assigning.

James
  • 4,146
  • 1
  • 20
  • 35