I came across some statements while surfing the .net source:
If( null != name)
If( false == check())
what is the difference between (name != null) and (Check() == false) statements from the above statements?
Can any one get me clear of this? Please.
I'm sure this is a duplicate, but I can't find it right now.
Code with the constant first is usually written by developers with an (old) background in C, where you might write this:
if (NULL == x)
instead of this:
if (x == NULL)
just in case you made a typo like this:
if (x = NULL) // Valid, but doesn't do what you want.
In most cases in C#, you don't need to do this - because the condition in an if statement has to be convertible to bool.
It would make a difference when you're comparing to a Boolean constant:
if ((Check() = false) // Eek!
... which is one reason to just write:
if (!Check())
Basically, putting the variable first is generally more readable - and in C# the reason for putting the constant first is almost never applicable anyway. (Modern C and C++ compilers will usually give you a warning anyway, so it's no longer a great idea in those languages either, as far as I'm aware...)
In terms of the order of evaluation, there is a theoretical difference in that the left-hand operand will be evaluated before the right-hand operand... but as the constants null and false don't have any side-effects, there's no real difference.
I think this style comes with C/C++ background, where the operator = which can also be used inside if statement, which could be used for comparison as well as assignment.
The statement
if( null != name) is same as if(name != null), so as the other statement
To safeguard from mistakenly assigning the value to the left hand side, this style of check is used in C/C++,
Take a look Coding Horror Yoda Conditions
Using if(constant == variable) instead of if(variable == constant),
like if(4 == foo). Because it's like saying "if blue is the sky" or
"if tall is the man".
The odd reversal looks like it was written by a C/C++ programmer... basically, in C/C++, if you accidentally type:
if(name = null)
instead of
if(name == null)
then that compiles and changes the value to null when invoked. A C/C++ habit to avoid this mistake is to use a constant such as null / false always on the left. This is because you can't reassign a constant, so it generates a compiler error if you use = instead of ==. In C# it (if(a = null)) doesn't usually compile, so that is not a concern.
There is no difference re the position here - both sides are evaluated. Idiomatic C# for this would be simply:
if(name != null) ...
if(!check()) ...
Related
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Conditional Statements difference
I wanted to know what is a good way of writing the code :
X != null
or
null != X
Both of them will do same thing, but sometimes I see people write null != X so I am not sure what is a good way of writing it.
The convention of reversing comparisons as null != X comes mainly from C where
if(X == NULL) {
is easily confused with
if(X = NULL) {
which is a valid statement that overwrites X with NULL instead of checking if it's NULL.
Turning the comparison the other way;
if(NULL == X) {
works just as well, but confusing the equals operator with assignment
if(NULL = X) {
will actually give a compilation error.
Common practice is to have the variable on the left-hand side: X != null. Putting the variable on the right-hand side is often called a "Yoda Condition".
Putting the literal on the left means that if you accidentally use = instead of == the compiler will complain. Also it can save on explicit null checks, for example (in Java)
if("hello".equals(someString))
returns false if someString is null.
I always use the format
<VAR> (!)= <VAL>
and never invert the order.
As you already said, both of them will do the same thing. The questions is about style so. Personally I would say x!=null is more readable.
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
What is wrong in comparing a null with an object rather than an object with a null
I see some developers using the following null object checking in C#:
if (null == myObject)
{
}
rather than:
if (myObject == null)
{
}
I prefer the second statement, since it reads naturally (for me) from left to right.
Is there any reason for why the first one would be used? Are there any performance benefits, or is it purely taste?
Some people (Mostly C developers) prefer the first way because if you forget one = sign the code wont compile in C.
For example, when i forget one =;
int a = 0;
if(a=1) //Accidental assignment, luckily the C# compiler warns us for this. The C compiler wouldnt.
{
}
if(1=a) // This is not logical, and not valid in either C# or C.
{
}
However as Jamietre pointed out that unlike C its invalid in C# to implicitly cast an int to a boolean. The compiler still produces an error. It will however work when you compare booleans as such: if(a == true). However that in itself is rather odd, as you can (and should in my opinion) omit the == true.
Purely taste. They both will return exactly the same thing.
Pure taste, same as with comas, brackets etc.
I just found out that I can compare null with an Object like this,
if(null != Object)
Rather than comparing Object with null, like
Object != null
What may go wrong if use the former approach?
Is that legal? If not then why does compiler accept it?
There's one thing wrong about it - readability. If you want to write a clean code, you should care about the way it will be read in the future. It needs to be obvious, what it does and why it does a certain thing. If you place the "Object" to the right of the evaluation, it becomes less apparent what are you really doing. Well at least in my opinion...
Most people say Object != null because it is what they are used to and so it is easier to read.
The best argument I've heard for null != object is to avoid bad expressions. e.g. to pickup a typo in if (var == 1)
if (var = 1) // this is valid C
if (1 = var) // this is not valid C
It's just a matter of readability. If you can read your code out loud and it makes sense it is easier to understand. The second version is like Yoda-talk.. "null is not the object.." compared the "The object is not null"..
This same goes for giving your variables and methods good names.
A good reference site for writing readable code: http://www.cleancoders.com/
It is the same. It is almost like saying if 1 != 2. Does this imply 2 != 1?
The != operator behaves just as the test for equality operator == .
Ignoring any side effects in the expressions then (expr1 != expr2) and (expr2 != expr1) are exactly the same.
If Object is a variable (or constant) then (null != Object) is just as valid (although a little bit less readable).
Surprisingly the code bellow will not succeed.
int? n1 = null;
int? n2 = null;
Assert.IsTrue(n1 <= n2); // Fails here
Do you know why?
Using boolean logic with null nullable values in C# (and VB.Net) often times defies logic. I find the best way to make sense of it is to remember that "null is not a value". Because null is not a value you cannot do any operations on it. Hence things like "1 > null" and "1 < null" are both true.
Here is a detailed guide: http://msdn.microsoft.com/en-us/library/2cf62fcy.aspx
If you do want to treat null as a value then you could use the GetValueOrDefaultMethod() to equate null with the default value. For example
Assert.IsTrue(n1.GetValueOrDefault() <= n2.GetValueOrDefault()); // True
This is a bit verbose but it will get the job done.
Either this is a typo and you meant "==" not "<=" or you misunderstand how nulls work.
In almost all languages (including c#) the only default legal operation on null is to check if something else is equal to it (in .Net == is by default reference equality).
<= and >= are not meaningful (as they would have very strange behaviour if they did)
Some languages (SQL being possibly the most well known) disallow the use of 'standard' equality operators to make this even more clear. in SQL null == null is NOT true, and a compliant server will refuse queries where you attempt to do this via a literal.
C# takes the same route as it's heritage (C style imperative languages) where the test for a null value is based on testing that the bits in it are zero (things get somewhat more complex but fundamentally that's what is happening). As such only reference types can truly be null (Nullable<T> has a lot of magic behind the scenes to make it look like it is but actually under the hood it isn't null). This means that the reference equality semantics follow nicely into null semantics, thus the == null is allowed.
Other languages implement null in a different fashion (for example SQL where anything can be made null thus the 'nullness' of something must be stored outside of it (much like Nullable). This means that the conventional use of equality need not be the primary concern and null can be truly special rather than a special case of certain types.
For further information on the specialness of null take a look at This question has a list of such languages
Most reference types do not define a >= or <= operator so there is little problem in practice with the disconnect between == and <= (where normally if something is true for == it would be true for <= and >= as well).
You can try this:
int? n1 = null;
int? n2 = null;
// Test for equality
Assert.IsTrue((n1.HasValue && n2.HasValue && n1.Value == n2.Value) || (!n1.HasValue && !n2.HasValue));
// Test for less than or equal to
Assert.IsTrue(n1.HasValue && n2.HasValue && n1.Value <= n2.Value);
Nullable types are wrapped into a System.Nullable object, so you don't compare the int value, you compare the reference. To compare the values, you need to make it like that:
Assert.IsTrue(n1.Value <= n2.Value);
I wrote a bit about nullable on my blog.
Edit:
But in your case n1 and n2 is null, so you can't even compare the values.
In c#, is there any difference in the excecution speed for the order in which you state the condition?
if (null != variable) ...
if (variable != null) ...
Since recently, I saw the first one quite often, and it caught my attention since I was used to the second one.
If there is no difference, what is the advantage of the first one?
It's a hold-over from C. In C, if you either use a bad compiler or don't have warnings turned up high enough, this will compile with no warning whatsoever (and is indeed legal code):
// Probably wrong
if (x = 5)
when you actually probably meant
if (x == 5)
You can work around this in C by doing:
if (5 == x)
A typo here will result in invalid code.
Now, in C# this is all piffle. Unless you're comparing two Boolean values (which is rare, IME) you can write the more readable code, as an "if" statement requires a Boolean expression to start with, and the type of "x=5" is Int32, not Boolean.
I suggest that if you see this in your colleagues' code, you educate them in the ways of modern languages, and suggest they write the more natural form in future.
There is a good reason to use null first: if(null == myDuck)
If your class Duck overrides the == operator, then if(myDuck == null) can go into an infinite loop.
Using null first uses a default equality comparator and actually does what you were intending.
(I hear you get used to reading code written that way eventually - I just haven't experienced that transformation yet).
Here is an example:
public class myDuck
{
public int quacks;
static override bool operator ==(myDuck a, myDuck b)
{
// these will overflow the stack - because the a==null reenters this function from the top again
if (a == null && b == null)
return true;
if (a == null || b == null)
return false;
// these wont loop
if (null == a && null == b)
return true;
if (null == a || null == b)
return false;
return a.quacks == b.quacks; // this goes to the integer comparison
}
}
Like everybody already noted it comes more or less from the C language where you could get false code if you accidentally forget the second equals sign. But there is another reason that also matches C#: Readability.
Just take this simple example:
if(someVariableThatShouldBeChecked != null
&& anotherOne != null
&& justAnotherCheckThatIsNeededForTestingNullity != null
&& allTheseChecksAreReallyBoring != null
&& thereSeemsToBeADesignFlawIfSoManyChecksAreNeeded != null)
{
// ToDo: Everything is checked, do something...
}
If you would simply swap all the null words to the beginning you can much easier spot all the checks:
if(null != someVariableThatShouldBeChecked
&& null != anotherOne
&& null != justAnotherCheckThatIsNeededForTestingNullity
&& null != allTheseChecksAreReallyBoring
&& null != thereSeemsToBeADesignFlawIfSoManyChecksAreNeeded)
{
// ToDo: Everything is checked, do something...
}
So this example is maybe a bad example (refer to coding guidelines) but just think about you quick scroll over a complete code file. By simply seeing the pattern
if(null ...
you immediately know what's coming next.
If it would be the other way around, you always have to scan to the end of the line to see the nullity check, just letting you stumble for a second to find out what kind of check is made there. So maybe syntax highlighting may help you, but you are always slower when those keywords are at the end of the line instead of the front.
I guess this is a C programmer that has switched languages.
In C, you can write the following:
int i = 0;
if (i = 1)
{
...
}
Notice the use of a single equal sign there, which means the code will assign 1 to the variable i, then return 1 (an assignment is an expression), and use 1 in the if-statement, which will be handled as true. In other words, the above is a bug.
In C# however, this is not possible. There is indeed no difference between the two.
In earlier times, people would forget the '!' (or the extra '=' for equality, which is more difficult to spot) and do an assignment instead of a comparison. putting the null in front eliminates the possibility for the bug, since null is not an l-value (I.E. it can't be assigned to).
Most modern compilers give a warning when you do an assignment in a conditional nowadays, and C# actually gives an error. Most people just stick with the var == null scheme since it's easier to read for some people.
I don't see any advantage in following this convention. In C, where boolean types don't exist, it's useful to write
if( 5 == variable)
rather than
if (variable == 5)
because if you forget one of the eaqual sign, you end up with
if (variable = 5)
which assigns 5 to variable and always evaluate to true. But in Java, a boolean is a boolean. And with !=, there is no reason at all.
One good advice, though, is to write
if (CONSTANT.equals(myString))
rather than
if (myString.equals(CONSTANT))
because it helps avoiding NullPointerExceptions.
My advice would be to ask for a justification of the rule. If there's none, why follow it? It doesn't help readability
To me it's always been which style you prefer
#Shy - Then again if you confuse the operators then you should want to get a compilation error or you will be running code with a bug - a bug that come back and bite you later down the road since it produced unexpected behaviour
As many pointed out, it is mostly in old C code it was used to identify compilation error, as compiler accepted it as legal
New programming language like java, go are smart enough to capture such compilation errors
One should not use "null != variable" like conditions in code as it very unreadable
One more thing... If you are comparing a variable to a constant (integer or string for ex.), putting the constant on the left is good practice because you'll never run into NullPointerExceptions :
int i;
if(i==1){ // Exception raised: i is not initialized. (C/C++)
doThis();
}
whereas
int i;
if(1==i){ // OK, but the condition is not met.
doThis();
}
Now, since by default C# instanciates all variables, you shouldn't have that problem in that language.