I have this piece of code in MyClass:
public static bool operator ==(MyClass lhs, MyClass rhs)
{
if (lhs == null || rhs == null)
return false;
// Other operations to check for equality
}
Going by the first line in the code, I'm comparing lhs and rhs to null. I'm not sure but I suppose that comparison itself will invoke the overload function again. And then we het to that line again, it invokes itself and so on. Sort of an infinite recursion.
But we all know that does not take place. This implies, in my opinion, that comparing with null does not invoke the equality overload. So what really occurs? How does comparing with null work?
EDIT
I stand corrected. It does call the == operator recursively (at least in LinqPad 4.5) rather than binding to object.==. There are three ways to fix this:
Overload Equals instead if you really want value equality semantics.
Cast lhs and rhs to object
Use Object.ReferenceEquals as the MSDN guidelines recommend
I suppose that comparison itself will invoke the overload function again
No - null is not a MyClass so the call uses the default meaning of == which is reference equality.
Also note that the guidelines for overloading == state that it should only be overloaded for immutable types, since the expected behavior for == is reference equality which is what happens by default. Equals implies "value equality" semantics.
In addition to D Stanley answer. To avoid such kind of surprizes (Object operator == is called), use Object.ReferenceEquals when implementing ==:
public static bool operator ==(MyClass lhs, MyClass rhs)
{
// lhs and rhs are the same instance (both are null included)
if (Object.ReferenceEquals(lhs, rhs))
return true;
else if (Object.ReferenceEquals(lhs, null) || Object.ReferenceEquals(rhs, null))
return false;
// From here we have different instances, none of them is null
// Other operations to check for equality
}
Related
I need to check if two objects of the same type are the same instances and point to the same allocation of memory. The problem is that the type has overloaded equality operator and thus it will use it as comparing the both for equality, but I need to check them for reference. I looked through object.ReferenceEquals() method, but it internally applies equality operator
Operators can't be overridden - they can only be overloaded.
So the == operator in object.ReferenceEquals is still comparing references, or you could do the same thing yourself by casting one or both operands:
string x = "some value";
string y = new string(x.ToCharArray());
Console.WriteLine(x == y); // True
Console.WriteLine((object) x == (object) y); // False
Console.WriteLine(ReferenceEquals(x, y)); // False
ReferenceEquals does exactly what you need, unless you're talking about a dictionary. It does not check Equals (it literally just does ldarg.0, ldarg.1, ceq, ret). Alternatively, just cast to object:
bool same = (object)x == (object)y;
If you need dictionary support (so: GetHashCode): System.Runtime.CompilerServices.RuntimeHelpers.GetHashCode(obj) is your friend.
Almost every time I want to check object's equality to null I use the normal equality check operation
if (obj == null)
Recently I noticed that I'm using the Object.Equals() more often
if (Object.Equals(obj, null))
and while reading about null checking I fount this Is ReferenceEquals(null, obj) the same thing as null == obj?
if (ReferenceEquals(null, obj))
Whats the difference? and where/when to use each one? plus I found that the last two checks look like the same according to their summary
Object.Equals(x, y) will:
Return true if x and y are both null
Return false if exactly one of x or y is null
Otherwise call either x.Equals(y) or y.Equals(x) - it shouldn't matter which. This means that whatever polymorphic behaviour has been implemented by the execution-time type of the object x or y refers to will be invoked.
ReferenceEquals will not call the polymorphic Equals method. It just compares references for equality. For example:
string x = new StringBuilder("hello").ToString();
string y = new StringBuilder("hello").ToString();
Console.WriteLine(Object.Equals(x, y)); // True
Console.WriteLine(Object.ReferenceEquals(x, y)); // False
Console.WriteLine(x == y); // True due to overloading
Now if you're only checking for nullity, then you don't really want the polymorphic behaviour - just reference equality. So feel free to use ReferenceEquals.
You could also use ==, but that can be overloaded (not overridden) by classes - it is in the case of string, as shown above. The most common case for using ReferenceEquals in my experience is when you're implementing ==:
public bool operator ==(Foo x1, Foo x2)
{
if (ReferenceEquals(x1, x2))
{
return true;
}
if (ReferenceEquals(x1, null) || ReferenceEquals(x2, null))
{
return false;
}
return x1.Equals(x2);
}
Here you really don't want to call the == implementation, because it would recurse forever - you want the very definite reference equality semantics.
While browsing the MSDN documentations on Equals overrides, one point grabbed my attention.
On the examples of this specific page, some null checks are made, and the objects are casted to the System.Object type when doing the comparison :
public override bool Equals(System.Object obj)
{
// If parameter is null return false.
if (obj == null)
{
return false;
}
// If parameter cannot be cast to Point return false.
TwoDPoint p = obj as TwoDPoint;
if ((System.Object)p == null)
{
return false;
}
// Return true if the fields match:
return (x == p.x) && (y == p.y);
}
Is there a specific reason to use this cast, or is it just some "useless" code forgotten in this example ?
It is possible for a type to overload the == operator. The cast to object ensures that the original definition is used.
As others said, the type might override the == operator. Therefore, casting to Objectis equivalent to if (Object.ReferenceEquals(p, null)) { ... }.
I believe casting to System.Object would get you around any operator overloading that TwoDPoint might have.
It likely exists to avoid confusion with an overloaded == operator. Imagine if the cast did not exist and the == operator was overloaded. Now the p == null line would potentially bind to the operator ==. Many implementations of operator == simply defer to the overridden Equals method. This could easily cause a stack overflow situation
public static bool operator==(TwoDPoint left, TwoDPoint right) {
return left.Equals(right);
}
public override bool Equals(System.Object obj) {
...
TwoDPoint p = obj as TwoDPoint;
if ( p == null ) { // Stack overflow!!!
return false;
}
...
}
By casting to Object the author ensures a simple reference check for null will occur (which is what is intended).
This might have been part of a larger sample where the == operator was overloaded. In that case, using obj == null could have resulted in StackOverflow if TwoDPoint.Equals(object) was invoked as part of the == definition.
Overloading the comparison operator, how to compare if the two variables points to the same object(i.e. not value)
public static bool operator ==(Landscape a, Landscape b)
{
return a.Width == b.Width && a.Height == b.Height;
}
public static bool operator !=(Landscape a, Landscape b)
{
return !(a.Width == b.Width && a.Height == b.Height);
}
Use the Object.ReferenceEquals static method.
Of course, in order for the == and != method to retain their full functionality, you should also be overriding Equals and GetHashCode so that they return a consistent set of responses to callers.
Try a.ReferenceEquals(b);
To check whether both points to same object. You should use Object.ReferenceEquals method. It will return true if both are same or if both are null. Else it will return false
I know its an old question, but if you're going to overload the == or Object.Equals method, you should also overload the reverse operator !=.
And in this case, since you're comparing internal numbers, you should overload the other comparison operators <, >, <=, >=.
People who consume your class in the future, whether it be third-party consumers, or developers who take over your code, might use something like CodeRush or Refactor, that'll automatically "flip" the logic (also called reversing the conditional) and then flatten it, to break out of the 25 nested if's syndrome. If their code does that, and you've overloaded the == operator without overloading the != operator, it could change the intended meaning of your code.
This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
How do I check for nulls in an '==' operator overload without infinite recursion?
When I overload the == operator for objects I typically write something like this:
public static bool operator ==(MyObject uq1, MyObject uq2) {
if (((object)uq1 == null) || ((object)uq2 == null)) return false;
return uq1.Field1 == uq2.Field1 && uq1.Field2 == uq2.Field2;
}
If you don't down-cast to object the function recurses into itself but I have to wonder if there isn't a better way?
As Microsoft says,
A common error in overloads of
operator == is to use (a == b), (a ==
null), or (b == null) to check for
reference equality. This instead
results in a call to the overloaded
operator ==, causing an infinite loop.
Use ReferenceEquals or cast the type
to Object, to avoid the loop.
So use ReferenceEquals(a, null) || ReferenceEquals(b, null) is one possibility, but casting to object is just as good (is actually equivalent, I believe).
So yes, it seems there should be a better way, but the method you use is the one recommended.
However, as has been pointed out, you really SHOULD override Equals as well when overriding ==. With LINQ providers being written in different languages and doing expression resolution at runtime, who knows when you'll be bit by not doing it even if you own all the code yourself.
ReferenceEquals(object obj1, object obj2)
#neouser99: That's the right solution, however the part that is missed is that when overriding the equality operator (the operator ==) you should also override the Equals function and simply make the operator call the function. Not all .NET languages support operator overloading, hence the reason for overriding the Equals function.
if ((object)uq1 == null)
return ((object)uq2 == null)
else if ((object)uq2 == null)
return false;
else
//return normal comparison
This compares them as equal when both are null.
Just use Resharper to create you Equals & GetHashCode methods. It creates the most comprehensive code for this purpose.
Update
I didn't post it on purpose - I prefer people to use Resharper's function instead of copy-pasting, because the code changes from class to class. As for developing C# without Resharper - I don't understand how you live, man.
Anyway, here is the code for a simple class (Generated by Resharper 3.0, the older version - I have 4.0 at work, I don't currently remember if it creates identical code)
public class Foo : IEquatable<Foo>
{
public static bool operator !=(Foo foo1, Foo foo2)
{
return !Equals(foo1, foo2);
}
public static bool operator ==(Foo foo1, Foo foo2)
{
return Equals(foo1, foo2);
}
public bool Equals(Foo foo)
{
if (foo == null) return false;
return y == foo.y && x == foo.x;
}
public override bool Equals(object obj)
{
if (ReferenceEquals(this, obj)) return true;
return Equals(obj as Foo);
}
public override int GetHashCode()
{
return y + 29*x;
}
private int y;
private int x;
}
But why don't you create an object member function? It can certainly not be called on a Null reference, so you're sure the first argument is not Null.
Indeed, you lose the symmetricity of a binary operator, but still...
(note on Purfideas' answer: Null might equal Null if needed as a sentinel value of an array)
Also think of the semantics of your == function: sometimes you really want to be able to choose whether you test for
Identity (points to same object)
Value Equality
Equivalence ( e.g. 1.000001 is equivalent to .9999999 )
Follow the DB treatment:
null == <anything> is always false