Reputation: 21
i wrote the following code in c#:
public class Person
{
private string idNumber;
private string personName;
public Person(string name, string id)
{
this.personName= name;
this.idNumber= id;
}
public override bool Equals(Objectobj)
{
Person personObj= obj as Person;
if(personObj== null)
return false;
else
return idNumber.Equals(personObj.idNumber);
}
public override int GetHashCode()
{
return this.idNumber.GetHashCode();
}
}
public static void Main()
{
Person p1 = new Person("John", "63412895");
Person p2 = new Person("Jack", "63412895");
Console.WriteLine(p1.Equals(p2));
Console.WriteLine(Object.Equals(p1, p2));
}
i don't understand why the second Console.WriteLine()
returns true???
the first returns true since i override equal method.
but the second one related to equal in object class.
please explain.
Upvotes: 1
Views: 304
Reputation: 6463
Quote from MSDN documentation on Object.Equals(Object, Object)
If the two objects do not represent the same object reference and neither is null, it calls objA.Equals(objB) and returns the result. This means that if objA overrides the Object.Equals(Object) method, this override is called.
I believe that's exactly what happens in your scenario. Since you have overridden the Equals
method, it is being called internally by the Object
's static method.
Upvotes: 2
Reputation: 14894
The static object.Equals
method is defined as
public static bool Equals(Object objA, Object objB)
{
if (objA==objB) {
return true;
}
if (objA==null || objB==null) {
return false;
}
return objA.Equals(objB);
}
So internally it uses the overriden Equals
after null
checks.
To compare references, use object.ReferenceEquals
or cast to object
and use ==
operator.
object.ReferenceEquals(p1, p2)
(object)p1 == (object)p2
Upvotes: 5
Reputation: 3683
The second line of code internally checks if p1 is null and calls the first line.
So you can't expect to have diferent results calling almost the same method.
p1.Equals(p2);
Object.Equals(p1, p2);
Upvotes: 1
Reputation: 1422
You overrode GetHashCode. That is what the object equality is using. The classic example is in .Net the two objects objStringA ="MyVal" and ObjStringB = 'MyVal" will return equal because the string overrides the get hash code.
It is like you overrode it twice. I am not sure you needed the Equals operator to be overridden in your case.
Upvotes: -1
Reputation: 307
I think it is related to the fact that you also override GetHashcode which is used by Object.Equals. That's my guess.
Upvotes: -1