Why does one often see “null != variable” instead of “variable != null” in C#?
I have seen senior developers using syntaxes mentioned in the title.
Is there a need for specifying a constant first in .NET? (as opposed to in C/C++ world)
The value null is written with a literal: null . null is not an identifier for a property of the global object, like undefined can be. Instead, null expresses a lack of identification, indicating that a variable points to no object.
Finally, if your code is specifically designed to rely on the pointer value being NULL or not NULL , it is perfectly fine to set the pointer value to NULL after free .
If a reference points to null , it simply means that there is no value associated with it. Technically speaking, the memory location assigned to the reference contains the value 0 (all bits at zero), or any other value that denotes null in the given environment.
A null value indicates a lack of a value, which is not the same thing as a value of zero. For example, consider the question "How many books does Adam own?" The answer may be "zero" (we know that he owns none) or "null" (we do not know how many he owns).
No, there's no need for this, because the problem it tries to avoid - namely the typo of:
if (variable = 0)
wouldn't compile in C# anyway. The conditions in if
statements have to be Boolean. There's still a risk of making one of these mistakes:
if (something = true)
if (something = false)
if something
is a Boolean variable, but the better way to fix this is to avoid the constant:
if (something)
if (!something)
If you have developers bringing over idioms like this from other languages without thinking about whether they're appropriate in C#, you should keep an eye for them doing more of the same. If you try to write C# as if it's C++ (or any other language, pretty much - with the possible exception of VB.NET) you'll end up writing non-idiomatic C# code.
EDIT: As cletus noted, there is another potential area for concern:
bool a = false, b = true;
if (a = b) { } // No warnings
So the error can still occur - but then we're outside the realm of comparing with a constant anyway :) I'd say this crops up incredibly rarely, and isn't worth too much time spent worrying about it.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With