Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does one often see "null != variable" instead of "variable != null" in C#?

In c#, is there any difference in the excecution speed for the order in which you state the condition?

if (null != variable) ... if (variable != null) ... 

Since recently, I saw the first one quite often, and it caught my attention since I was used to the second one.

If there is no difference, what is the advantage of the first one?

like image 613
mr_georg Avatar asked Nov 07 '08 08:11

mr_georg


People also ask

What is the difference between null != And != null?

If the operands of an equality operator are both of either reference type or the null type, then the operation is object equality. The result of != is false if the operand values are both null or both refer to the same object or array; otherwise, the result is true . Use whatever is most readable.

What does != null mean in C#?

The null keyword is a literal that represents a null reference, one that does not refer to any object. null is the default value of reference-type variables. Ordinary value types cannot be null, except for nullable value types. The following example demonstrates some behaviors of the null keyword: C# Copy.

How do you set a variable to equal null?

To set the value of a variable is it's equal to null , use the nullish coalescing operator, e.g. myVar = myVar ?? 'new value' . The nullish coalescing operator returns the right-hand side operand if the left-hand side evaluates to null or undefined , otherwise it returns the left-hand side operand.

What does it mean if an object variable is null?

The null value simply means that the variable does not refer to an object in memory.


1 Answers

It's a hold-over from C. In C, if you either use a bad compiler or don't have warnings turned up high enough, this will compile with no warning whatsoever (and is indeed legal code):

// Probably wrong if (x = 5) 

when you actually probably meant

if (x == 5) 

You can work around this in C by doing:

if (5 == x) 

A typo here will result in invalid code.

Now, in C# this is all piffle. Unless you're comparing two Boolean values (which is rare, IME) you can write the more readable code, as an "if" statement requires a Boolean expression to start with, and the type of "x=5" is Int32, not Boolean.

I suggest that if you see this in your colleagues' code, you educate them in the ways of modern languages, and suggest they write the more natural form in future.

like image 151
Jon Skeet Avatar answered Oct 05 '22 20:10

Jon Skeet