I have a class named Employee. Now I try to define its Equals method, but I want to accept an Employee as parameter only.
So I write this code:
class MainClass
{
public static void Main (string[] args)
{
Employee e = new Employee();
Employee e2 = new Employee();
Console.WriteLine(Equals(e, e2));
}
public static Employee CreateEmployee()
{
return new Employee();
}
}
class Employee
{
public int ID;
public bool Equals (Employee e)
{
Console.WriteLine("Compare!");
return ID == e.ID;
}
}
But it doesn’t work! The console outputs:
false
Not what I expected:
Compare!
true
It looks like that I have to write public override bool Equals (Object), but why? Can’t C# choose the method to call by the type of parameter(s)?
Try changing your code to
As you had it it was using Object.Equals Method (Object, Object)