In C#, why is null != variable
preferred instead of variable != null
?
In C# code, the habit of using null != variable
instead of variable != null
stems from the historical convention of the C language.
In C language, the =
operator represents both assignment and equality checking, which can lead to errors in which programmers accidentally use the assignment operator instead of equality checking, for example:
<code class="language-c">if (x = 5) // 将 5 赋值给 x,而不是检查相等性</code>
To avoid such errors, C programmers often use 5 == x
to ensure that an equality check is intended.
In C#, comparison operators are strictly defined as equality checks, eliminating ambiguities in the C language. Therefore, there is no technical advantage to putting null
in front of variables in equality checks.
variable != null
However, the variable != null
form is generally considered more readable and concise. Since null
indicates the absence of a value, it makes more sense to test for its absence by declaring "if the variable is not null":
<code class="language-csharp">if (variable != null) ...</code>
While the historical reasons for placing null
before variables in C# no longer apply, the practice is still carried over from the C language. However, there are no performance or functional differences between the two forms, and the variable != null
form is generally preferred for its clarity and simplicity.
The above is the detailed content of Is `null != variable` or `variable != null` Better in C#?. For more information, please follow other related articles on the PHP Chinese website!