If I have a object like:
public class Person
{
public int id {get;set;}
public string name {get;set;}
}
And I want the behavior:
Person a = new Person();
Person b = new Person();
a == b;
and that a == b returns true, do I have to override the Object.Equals() method? or is there some other way of doing it without overriding the Equals method?
EDIT
I want to compare data, as I want to know if a external method that I call returns a new object or a object with different data than a new object
Suppose Test is Class
Yes. You want to compare to objects of Person, you need to override equals and hashcode method from Object class as by default reference check (==) is done through equals method.
Assuming two Persons with same name and id can only be considered equal use both of these properties in equals and hashcode method.
Generating equals and hashcode has beocme easier with the Java IDE's provided. U can try below code.
in your case:
There are a couple of ways you can do this. By default
Equals()
and==
check for reference equality, meaning:And therefore, the objects are not compared for value equality, meaning:
To compare objects for their values you can override the
Equals()
andGetHashcode()
methods, like this:Now you will see other results when comparing:
The
==
operator is not overridden and therefore still does reference comparison. This can be solved by overloading it as well as the!=
operator:Now running the checks results in following:
More reading:
This all depends on what you are trying to compare, by default
Equals
will compare by reference thereforein your example will always be
false
. However, if you did something likeThen
a == b
would betrue
because botha
andb
are using the same reference.Overriding Equals and GetHashCode is the recommended approach, however, (for arguments sake) it's not the only way. You could, for example, override the
==
operator and do your comparison in there. However, there are limitations with going down that route alone.Most comparison checks, if not all, will use
Equals
internally which is why it's the preferred approach. See Guidelines for Implementing Equals and the Equality Operator (==).You want to overload the
==
operator. Therefore you should also overrideEquals
first. If you overrideEquals
you should always also overrideGetHashCode
. If you overload the==
operator you must also overload the!=
operator:Now this compares values (the
id
) instead of only references:MSDN: Guidelines for Implementing Equals and the Equality Operator (==)