(0 == variable) or (null == obj): An outdated practice in C#? [duplicate]

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.

Leave a Comment