Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Conditional Statements difference

Tags:

c#

asp.net

Is there any difference between below two statements

if (null != obj)

and

if (obj != null)

If both treated same which will be preferable?

like image 369
Muhammad Akhtar Avatar asked Feb 10 '11 13:02

Muhammad Akhtar


2 Answers

The first is a Yoda condition. Use it you should not.

like image 187
TimC Avatar answered Oct 23 '22 20:10

TimC


The difference here is the code generated. The two will not generate the exact same code, but in practice this will have no bearing on the results or performance of the two statements.

However, if you create your own types, and override the inequality operator, and do a poor job, then it will matter.

Consider this:

public class TestClass
{
    ...

    public static bool operator !=(TestClass left, TestClass right)
    {
        return !left.Equals(right);
    }
}

In this case, if the first argument to the operator is null, ie. if (null != obj), then it will crash with a NullReferenceException.

So to summarize:

  • The code generated is different
  • The performance and end results should be the same
    • Except when you have broken code in the type involved

Now, the reason I think you're asking is that you've seen code from C, which typically had code like this:

if (null == obj)

Note that I switched to equality check here. The reason is that a frequent bug in programs written with old C compilers (these days they tend to catch this problem) would be to switch it around and forget one of the equal characters, ie. this:

if (obj = null)

This assigns null to the variable instead of comparing it. The best way to combat this bug, back then, would be to switch it around, since you can't assign anything to null, it's not a variable. ie. this would fail to compile:

if (null = obj)
like image 7
Lasse V. Karlsen Avatar answered Oct 23 '22 21:10

Lasse V. Karlsen