Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the best syntax for checking for null value objects in C#

Tags:

c#

It always feels wrong to me to write

if (MyObject)
    // do something

Or reversly

if (!MyObject)
    // do something

However you could argue that it is less verbose than

if (MyObject != null)
    // do something

if (MyObject == null)
    // do something

Are there any non-subjective reasons to use one over the other?

like image 610
Nick Allen Avatar asked Nov 26 '22 21:11

Nick Allen


1 Answers

In C#, you can't do

if (MyObject) 

to check for nulls. It's a compile time error (if the class doesn't have an implicit boolean conversion operator).

if (!MyObject)

is also invalid if the class doesn't overload operator ! to return a boolean value (or a value that can be implicitly casted to a boolean).

So you have to stick with obj == null and obj != null.

To summarize, the non-subjective reason is being able to compile your code!

UPDATE (story):

Once upon a time, in ancient C, there was no bool type. Zero was considered false and every non-zero value was considered true. You could write

while(1) { }

to create an infinite loop.
You could also do things like

int n  = 10;
while (n--) { }

to have a loop that executes n times. The problem with this strategy was:

int x = 10;
if (x = 0) { // bug: meant to be x == 0
}

You missed a single character and you created a bug (most modern C compilers will issue a warning on this statement, but it's valid C, nevertheless).

This is why you see code like

if (5 == variable) 

if (NULL == pObj)

in many places as it's not prone to the above mistake.

C# designers decided to require a boolean expression as the condition for if, while, etc., and not allow casting of types (unless they explicitly declare an overloaded operator, which is discouraged) to boolean to reduce the chance of errors. So things like:

object x = null;
if (x) { }

int y = 10;
if (y) { }
while (y--) { }

that are valid in C, do not compile in C# at all.
This is not a matter of style or agreement by any means.

like image 62
mmx Avatar answered Nov 29 '22 11:11

mmx