Conditional Statements difference - c#

Is there any difference between below two statements
if (null != obj)
and
if (obj != null)
If both treated same which will be preferable?

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

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)

No, but the second way is more common and more readable (and more logical in my opinion)

No, there is not. It's exactly the same.
The style null == obj is sometimes just used to prevent the common typo obj = null to not accidently assign null to a variable, but with != there's absolutely no reason to do so.
In .NET it won't actually compile for the typo obj = null.
So the compiler prevents you from accidently doing it.
The Yoda condition comes originally from other languages, where this compiler feature is missing.

They are exactly the same.
Some people prefer to put the null as the first part of the expression to avoid errors like this
if (obj = null) // should be obj == null
But of course this doesn't apply to the != operator, so in your example it's just a difference of style.

First type of statement came from C/C++, where was possible to pass not boolean values to condition verification. E.g. anything not 0 was true, and zero was false:
if (5) { } // true
if (0) { } // false
Sometimes it created problems if you forgot to type one '=' char:
if (x = 5) { } // this was true always and changed x value
if (x == 5) { } // this was true, if x was equal to 5
So, Yoda syntax was used, to receive compiler error in case one '=' was missed:
if (5 = x) { } // this was generating compiler error for absent-minded programmers
if (5 == x) { } // this was true, if x was equal to 5
C# allow only boolean value in conditions, So
if (x = 5) { } // this won't compile
if (x == 5) { } // this is true, if x was equal to 5
What about boolean types?
if (y = true) { }
if (y == true) { }
Well, this is useless code, because you can just write if (y).
Conclusion: Yoda syntax is gone with C/C++ and you do not need to use it anymore.

The use of the first form
if (blah == obj)
stems from the days when compilers would not catch if (obj = blah) i.e. unintentional assignment, unless compile warning level was set to maximum

Related

bool? compare with bool vs GetValueOrDefault vs ?? operator

With numeric it is always same pretty:
if(a < 123) { ... } // disregards if `b` is `int?` or `int`
But with bool?:
bool? b = ...
if(b) { ... } // compiler error: can't convert bool? to bool.
There are following options:
if(b == false) { ... } // looks ugly, comparing bool? with bool
if(b.GetValueOrDefault()) { ... } // unclear when condition is true (one must know it's `false`)
if(b.GetValueOrDefault(true)) { ... } // required few seconds to understand inversion
I was curios whenever nullables (at least bool?) deserves this syntax to be used always:
if(b ?? false) { ... } // looks best to me
P.S.: this may looks like opinion-based question, but I didn't find similar to clear all my doubts alone... Perhaps some of those are best used in certain scenarios and I'd like to know in which ones.
The language designers had two choices, as far as allowing bool? to participate in control expressions of control statements requiring a bool:
Allow it, and make an arbitrary decision when it comes to null treatment
Disallow it, forcing you to make a decision each time it is relevant.
Note that the designers had much less of an issue with if(a < 123) statement, because "no" is a valid answer to questions "is null less than 123", "is null greater than 123", "is null equal to 123", and so on.
The if (b ?? false) and if (b ?? true) are very convenient constructs, which let you explain to the readers of your code and to the compiler in which way you wish to treat nulls stored in a bool? variable.
Every time I see someone using a nullable boolean bool?, I ask them why. Usually, the answer is -- "well, I'm not really sure". It is effectively creating a three state condition which in my opinion makes the code harder to read regardless. What does null mean, if it is always false then why bother with making it nullable in the first place?
But to answer your question more directly, I prefer the
if (b ?? false)
syntax over the
if (b.GetValueOrDefault())
Some years later and from personal experience I can tell that following syntax is clearly a winner:
if(b == false) { /* do something if false */ }
if(b == true) { /* do something if true */ }
if(b != false) { /* do something if NOT false, means true or null */ }
if(b != true) { /* do something if NOT true, means false or null */ }
What I thought as "ugly" turns out to be the easiest to understand.
== vs ??
Nullables are often results of linq queries and using ?? add unnecessary layer of complexity to understand the condition.
Compare
if(Items?.Any(o => o.IsSelected) == true)
vs
if(Items?.Any(o => o.IsSelected) ?? false)
The first one is much easier to read, it's a simple check if any item is selected.
When my (probably untrained?) mind reads the latter, I have to make a mental full stop at ??, do inversion and only then I understand when if block will be executed. With ?? I am likely to make a mistake when quickly looking throught the code written by someone else or even my own code given enough time has passed.

Does the order of operands matter for an overloaded == operator in C#

I am using a 3rd party tool (Unity3d), where one of the fundamental base classes overloads the == operator (UnityEngine.Object).
The overloaded operator's signature is:
public static bool operator == (UnityEngine.Object x, UnityEngine.Object y)
Does the order in which the comparison is made have any effect on whether this overloaded operator is used ?
To illustrate, should both of these use the overloaded operator and return the same result ?
// initialize with some value
UnityEngine.Object a = ....
Debug.Log(a == null);
Debug.Log(null == a);
The reason i'm asking is because i'd like to (sometimes) avoid this overloaded behaviour (use the default == operator), and was wondering whether flipping the order would assist in that ?
(There could be another option - casting the operands to System.object, but I am not 100% sure that works).
Well, it's possible that the two calls wouldn't be the same, if the operator had been overloaded badly. Either there could be one overload, and it could be written in a way which compares the operands asymmetrically, or the two statements could call different overloads.
But assuming it's been overloaded properly, that should be absolutely fine. That's if you want to call the overloaded operator, of course. In situations where you don't, I'd make that clear using ReferenceEquals.
I would personally recommend the if (a == null) approach, as I find it easier to read (and I believe many others do too). The "yoda" style of if (null == a) is sometimes used by C programmers who fear typos, where if (a = null) would be an assignment and a valid statement... albeit with a warning in decent C compilers.
Here's an example of a badly implemented set of overloads, where the operand order matters, because null is convertible to both string and Test:
using System;
class Test
{
public static bool operator ==(Test t, string x)
{
Console.WriteLine("Test == string");
return false;
}
public static bool operator !=(Test t, string x)
{
Console.WriteLine("Test != string");
return false;
}
public static bool operator ==(string x, Test t)
{
Console.WriteLine("string == Test");
return false;
}
public static bool operator !=(string x, Test t)
{
Console.WriteLine("string != Test");
return false;
}
static void Main(string[] args)
{
Test t = null;
Console.WriteLine(t == null);
Console.WriteLine(null == t);
}
}
Now that the question has been updated, we can tell that's not the case... but the implementation could still be poor. For example, it could be written as:
public static bool operator == (UnityEngine.Object x, UnityEngine.Object y)
{
// Awful implementation - do not use!
return x.Equals(y);
}
In that case, it will fail with a NullReferenceException when x is null, but succeed if x is non-null but y is null (assuming Equals has been written properly).
Again though, I'd expect that the operator has been written properly, and that this isn't a problem.
UPDATE after updating the question:
If you want to avoid calling the overloaded function when comparing to null, use ReferenceEquals:
if(a.ReferenceEquals(null)) ...
OLDER ANSWER, RENDERED OBSOLETE AND ALSO WRONG BY #Jon Skeet...
According to this, overload resolution of binary operator with X and Y as arguments is done by first taking the union of all operators defined by X and by Y.
So a==b results in exactly the same overload resolution as b==a.
The link is from 2003, but I doubt Microsoft has changed something since, it would have broken a lot of older code.
Update: Although I witnessed this behaviour in prior versions of Unity, I couldn't reproduce it in a test I performed right after writing this answer. May be Unity changed the == operator behaviour, or behaviour of implicit conversion of UnityEngine.Object to bool; however, I would still advocate using the overridden == operator instead of trying to avoid it.
The way Unity in particular overrides == operator is very frustrating, but also fundamental for how you have to work with the engine. After the UnityObject gets destroyed, by calling Destroy (some time after the call) or DestroyImmediate (immediately after the call, as the name would suggest), the comparison of this object to null returns true, even though it's not a null reference.
It's completely unintuitive for C# programmers, and can create a lot of truly WTF moments before you figure this out. Take this, for example:
DestroyImmediately(someObject);
if (someObject)
{
Debug.Log("This gets printed");
}
if (someObject != null)
{
Debug.Log("This doesn't");
}
The reason I'm explaining that is because I perfectly understand your desire to avoid this strange overridden behaviour, especially if you had C# experience before working with Unity. However, as with a lot of other Unity-specific stuff, it might actually be better to just stick to the Unity convention instead of trying to implement everything in the C#-correct way.

Result of calling IEquatable<T>.Equals(T obj) when this == null and obj == null?

What should IEquatable<T>.Equals(T obj) do when this == null and obj == null?
1) This code is generated by F# compiler when implementing IEquatable<T>. You can see that it returns true when both objects are null:
public sealed override bool Equals(T obj)
{
if (this == null)
{
return obj == null;
}
if (obj == null)
{
return false;
}
// Code when both this and obj are not null.
}
2) Similar code can be found in the question "in IEquatable implementation is reference check necessary" or in the question "Is there a complete IEquatable implementation reference?". This code returns false when both objects are null.
public sealed override bool Equals(T obj)
{
if (obj == null)
{
return false;
}
// Code when obj is not null.
}
3) The last option is to say that the behaviour of the method is not defined when this == null.
leppie is right. Just to elaborate on his answer (and confirm his suspicion that F# doesn't guarantee this != null): discriminated unions may be marked with the attribute [<CompilationRepresentation(CompilationRepresentationFlags.UseNullAsTrueValue)>] allowing cases to be represented by the value null. Option<'T> is such a type. The None case is represented by null at run-time. (None : option<int>).Equals(None) is syntactically valid. Here's a fun example:
[<CompilationRepresentation(CompilationRepresentationFlags.UseNullAsTrueValue)>]
type Maybe<'T> =
| Just of 'T
| Nothing
[<CompilationRepresentation(CompilationRepresentationFlags.Instance)>]
member this.ThisIsNull() = match this with Nothing -> true | _ -> false
Decompiling ThisIsNull with Reflector shows
public bool ThisIsNull()
{
return (this == null);
}
And the result:
Nothing.ThisIsNull() //true
The reason F# does this (I suspect) to optimize empty lists as null.
By adding this check, it allows one to call an instance method on a null instance without any problems.
See my blog post from a while back.
In C#, this is irrelevant.
To answer the question:
It should return true as both instances are null and deemed equal.
If this is null, the code can't be called, so that case needn't be considered (in C# anyway, there are cases where languages allow a null object to have a method dereferenced though obviously if it internally examines any of its non-existent fields it will error. Consider:
return x.Equals(y);
If x is null, we don't even get to call into Equals for the null check to count.
Hence we need only consider:
public bool Equals(T obj)
{
if(obj == null)
return false;
//logic defining equality here.
}
Where the possibility of both objects being null does come up, is when we are examining them from a static == operator override or from an IEqualityComparer<T> implementation:
public bool Equals(T x, T y)
{
if(x == null)
return y == null;
if(y == null)
return false;
//logic defining equality here.
}
Note that a useful shortcut here if equality can be lengthy to determine (e.g. comparing long strings), then we may take advantage of the fact that identity entails equality - that is something is always equal to itself, even Ayn Rand could figure that out ;) There are also algorithms that make comparing an item with itself quite common, making this shortcut well worth including. In this case the identity comparison already includes the check for both being null, so we leave it out again:
public bool Equals(T x, T y)
{
if(ReferenceEquals(x, y))
return true;
if(x == null || y == null)
return false;
//logic defining equality here.
}
For most methods I assume undefined behavior when called with this==null. That's because most programmers write their code under the assumption that this!=null, which is guaranteed by the C# specification if the calling code is written in C#.
That's why every sane caller of x.Equals(y) should either know for sure that that x is not null, or add a manual null check.
In most cases I wouldn't call Equals directly at all, but instead use EqualityComparer<T>.Default.
I would definitelly go with option 1:
if (this == null)
{
return obj == null;
}
if (obj == null)
{
return false;
}
null object always equals null object.
Sample code is in the MSDN: http://msdn.microsoft.com/en-us/library/ms131190.aspx?ppud=4
If this==null you will get a runtime exception calling Equals() on that object.

Difference between Forward and Reverse Comparison in C#

this is related to comparing values in C#.
basically by default, in C# till date i only used forward comparison as follows:
string value1 = "";
if (value1 == null)
{
Console.WriteLine("True");
}
else
{
Console.WriteLine("False");
}
somewhere on Internet, i came across a link where it is said that while comparing values in C#, we should prefer Reverse Comparison as :
string value1 = "";
if (null == value1)
{
Console.WriteLine("True");
}
else
{
Console.WriteLine("False");
}
Now the problem is that is there any basic difference between the two ways of comparing values or not (i.e. both are same).
Looking for favorable replies.
Thanks
This is a hangover from languages where values are implicitly converted to a boolean type.
For the most part, anything that was non-null or non-0 would be treated as true, otherwise it was equivalent to false. This meant that any assignation of a constant would always be true.
This thing to remember here is that the assignment function returns the value assigned, much in the same way that 5 is the result of 2+3, myInt = 5 also returns 5.
Because of this, it was recommended that you check the variable against the constant. The null example is actually probably a bit contrived in this case, as it would, in most languages, return as false.
As an example:
if(i = 1)
{
printf("Always out\n");
}
else
{
printf("Never prints\n");
}
i is assigned the value of 1, which then returns the value of the assignment, 1, to the if statement. This is equivalent to true, and the if condition matches.
If you were to attempt to assign i to the constant 1, you wouldn't compile, and so it was recommended that you do things it that order (e.g. 1 == i).
This is not neccesary in C#, and further to your example, the recommended practice is to call if(String.IsNullOrEmpty(myStringValue)) { //.... }, as a string has... two ... default values from a semantic perspective.
Reverse comparison protects you from errors, when you use == (compare) instead of = (assign). But complier also warns you if you do this.

Is there any difference between if(a==5) or if(5==a) in C#? [duplicate]

This question already has answers here:
Closed 13 years ago.
Just I would like to know, is there any difference between
if (a==5) or if (5==a)
in C#, Which one is better?
There's no difference - assuming that "a" is an integer.
I know some people prefer if (5==a) because in c & c++ if you wrote if (5=a) by mistake you'd get a compiler error while if (a=5) would result in a bug.
C# raises a compiler error in the latter case, so it's not an issue.
I'd actually say there is a difference, but it's not a technical one (as everyone has well covered already) - readability. It matters and the first form is much more natural.
The if(5 == a) construct is common in C/C++ because boolean values are represented using ints. Thus if you write a = 5 by mistake this can be evaluated in the context of the if, which is most likely not what you wanted.
In C# there's no implicit conversion from int to bool, so if you type = instead of == you'll get a compile error.
no difference, it is an old habit to avoid if(a=5) in c/c++.
These questions/answers are about the same:
(0 == variable) or (null == obj): An outdated practice in C#?
Checking for null, which is better? "null ==" or "==null"
Why does one often see "null != variable" instead of "variable != null" in C#?
Both are equivalent.
I remember when I used to code in C, I preferred 'if (5==a)' because it guarantees that I haven't typed 5=a accidentally as the compiler would throw error. This would not happen if we write 'if (a=5)'. Though it is a typo, it would not generate any compiler error and would go unnoticed.
But, in C# it is not the case. There is no logical reason to write 'if (5==a)'. If we had written 'if(a=5)', the compiler would throw an error. So in C# use 'if(a==5)'!
With correct design, there is no difference between "a == 5" and "5 == a". But there is some special situation, where has "a == 5" and "5 == a" different behaviour. It's very unpropably, but it is posible.
Nevertheless this example is constructed for demonstration of the situation, and I does not recomend do thinks such this.
Example:
public class BadClass {
public int Value;
public static implicit operator int( BadClass c ) {
return c.Value;
}
//public static implicit operator BadClass( int n ) {
// return new BadClass { Value = n };
//}
public static bool operator ==( BadClass c, int n ) {
return (c.Value + 1 == n);
}
public static bool operator !=( BadClass c, int n ) {
return (c.Value + 1 != n);
}
public override bool Equals( object obj ) {
if ( obj is int ) {
return (this == (int)obj);
}
else {
return base.Equals( obj );
}
}
public override int GetHashCode() {
return base.GetHashCode();
}
}
...
BadClass a = new BadClass { Value = 13 };
var rslt_1 = (13 == a); //there will be true
var rslt_2 = (a == 13); //there will be false
Other than the safety if (5==a) gives you, No.
Only difference is if you forget the second equals, the first version is still a valid statement whereas the second version will raise a compile time error.
HTH
cheers,

Categories

Resources