This question and Jon's answer made me aware this even existed, so I got curious and launched Visual Studio.
I followed along one example of the MSDN page, and then I created my own little example. It's as follows:
public class Person : IEquatable<Person>
{
public string IdNumber { get; set; }
public string Name { get; set; }
public bool Equals(Person otherPerson)
{
if (IdNumber == otherPerson.IdNumber)
return true;
else
return false;
}
public override bool Equals(object obj)
{
if (obj == null)
return base.Equals(obj);
if (!(obj is Person))
throw new InvalidCastException("The Object isn't of Type Person.");
else
return Equals(obj as Person);
}
public override int GetHashCode()
{
return IdNumber.GetHashCode();
}
public static bool operator ==(Person person1, Person person2)
{
return person1.Equals(person2);
}
public static bool operator !=(Person person1, Person person2)
{
return (!person1.Equals(person2));
}
}
So I have a couple of questions:
If the Equals method does a good job at handling my custom equality, why do I have to override the GetHashCode method as well?
When comparing something like below, which comparer is used, the Equals or the GetHashCode?
.
static void Main(string[] args)
{
Person sergio = new Person() { IdNumber = "1", Name = "Sergio" };
Person lucille = new Person() { IdNumber = "2", Name = "Lucille" };
List<Person> people = new List<Person>(){
sergio,
lucille
};
Person lucille2 = new Person() { IdNumber = "2", Name = "Lucille" };
if (people.Contains(lucille2))
{
Console.WriteLine("Already exists.");
}
Console.ReadKey();
}
- What exactly do the operator method do? It looks like some sort of voodoo black magic going on there.