Nalaka526
Nalaka526

Reputation: 11484

Checking for null, == null vs != null

Is there a recommended way (according to .net Framework guidelines) of checking for null, example:

if (value == null)
{//code1}
else
{//code2}

or

if (value != null)
{//code2}
else
{//code1}

Or the both codes has same performance?

Upvotes: 2

Views: 285

Answers (5)

NoobieDude
NoobieDude

Reputation: 93

both are same.. for readability you can put the block of code in IF which gives the result as true. In this case IF(value != null) is better readable and obvious :)

Upvotes: 0

Yogendra Singh
Yogendra Singh

Reputation: 34387

There is no performance difference. Use them as per your need(readability/usability perspective). Most appropriate/used block goes in if and the optional/secondary block goes in else.

Upvotes: 2

xxbbcc
xxbbcc

Reputation: 17346

There's no difference in performance. I personally put the more common case on top and the less common case in the else branch but that's just preference. This makes it easier for me to see the more common scenario.

Upvotes: 4

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 726987

There is no performance difference, so you should strive for improved readability.

For example, it is often a good idea to put the more "regular" path in the if branch, and put the "exceptional" one in the else branch.

Upvotes: 11

SLaks
SLaks

Reputation: 888107

Both options will perform identically.

You should use whichever one makes sense semantically, or whichever one results in cleaner code.
For example, if the non-null action is shorter, it makes sense to put that block first, so that the else is close to the if.

Upvotes: 15

Related Questions