End Google Ads 201810 - BS.net 01 --> They both appear to do the same thing, except Object.Equals documentation says that it throws a NullReferenceException. I can't get it to do that though.

They both test for equality of instances, they both take the same parameters, and they are both static members of System.Object.

I am implementing equality comparison using the standard overrides and operator overloads. I am frustrated with these little details that seem unnecessary.

Documentation says:


Object.ReferenceEquals Method
Determines whether the specified Object instances are the same instance.


Object.Equals Method
Determines whether two Object instances are equal.


EDIT:

I figured it out, I stepped through the code and learned that the static Object.Equals(object a, object b) called in the operator overload actually makes a call to the virtual instance-level Equals(object obj), so the static ReferenceEquals has to be used to test for instance equality. Though by default the static Object.Equals(object a, object b) will do the same thing as the static ReferenceEquals, unless you override the instance-level Equals method, because by default, the instance-level equals tests for instance equality.


public class Foo : IEquatable
{
public static bool operator !=(Foo foo1, Foo foo2)
{
return !Equals(foo1, foo2); //under the hood, this STATIC, note STATIC method makes a call to the
// INSTANCE-level Equals(object obj) method.
}

public static bool operator ==(Foo foo1, Foo foo2)
{
return Equals(foo1, foo2); //under the hood, this STATIC, note STATIC method makes a call to the
// INSTANCE-level Equals(object obj) method.
}

public bool Equals(Foo foo)
{
if (foo == null) return false;
return y == foo.y && x == foo.x;
}

public override bool Equals(object obj) //called by the static object.Equals(obj, obj) method
{
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;
}


Watch the Fall of the Republic (High Quality 2:24:19)[^]

modified on Thursday, October 29, 2009 2:48 PM