0

I have the following:

public abstract class Person
{
    public DateTime CreatedAt { get; set; }
    
    public abstract bool IsMatch(Person person);
}

public class Employee : Person
{
    public int Id { get; set; }
    public string Role { get; set; }

    public override bool IsMatch(Employee person)
    {
        return Id == person.Id;
    }
}

The compiler doesn't like my override of the IsMatch method.

  1. Why is this? Empolyee is a Person so why is it complaining?
  2. What is the best way around this? Would I need to cast to Employee in the IsMatch override?

Thanks.

James
  • 1,979
  • 5
  • 24
  • 52
  • 1
    `Person` and `Employee` are different types, `IsMatch` should have the same signature – Pavel Anikhouski Jun 30 '20 at 14:37
  • Perhaps you should dig into https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/statements-expressions-operators/how-to-define-value-equality-for-a-type and or the hash code. – Andy Stagg Jun 30 '20 at 14:46

1 Answers1

4

Why is this? Empolyee is a Person so why is it complaining?

Because you have to override with the same signature, not one that's similar. In some cases it would seem reasonable, but in this case it's definitely not reasonable. Consider the following:

public class Customer : Person
{
}
...

Person employee = new Employee();
Person customer = new Customer();
bool match = employee.IsMatch(customer);

That should definitely compile with no problems - I'm calling IsMatch on the abstract Person class; the compiler doesn't "know" that employee actually refers to an Employee. So how would you expect that to execute? It couldn't enter your implementation of IsMatch, because we're passing a customer.

What is the best way around this?

That's hard to say without knowing more about the situation. You could implement Employee.IsMatch like this instead:

public override bool IsMatch(Person person) =>
    person is Employee employee && Id == employee.Id;

That may be the right thing to do, but we don't really know.

Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194