I have an object of type Foo.
Foo has an Id (int)
a) Is the code bellow “good”?
b) What should I return if both are null?
// overload operator ==
public static bool operator ==(Foo a, Foo b)
{
if (ReferenceEquals(x, y))
{
return true;
}
if (x == null && y == null)
{
return // ???
}
if (x == null || y == null)
{
return false;
}
return x.Id == y.Id; // Ids are the same
}
public static bool Equals(Foo x, Foo y)
{
return x == y;
}
EDIT:
c) Should the Equals method call the == operator, or viceversa?
Last question
d) Is it possible that
ReferenceEquals(x, y) == true AND x.Id != y.Id?
Yes
nullis nothing but internal Pointer with value zero. So it is comparing two references having value zero.In fact
object.ReferenceEquals(null, null)is always true because of this fact so you do not need the second check.On the last point, == and Equals are handled the same unless on the boxed value types:
This produces
falseandtrue.Point d: NO it is the same object, the same memory space – if they are pointing to a field on the object.