I have a mess when I combine interfaces and polymorphism.
Say I have the following interface:
public Interface CanSayHello
{
String SayHello();
}
The following class:
public Class Person : CanSayHello
{
public String SayHello() { return "Hey, I'm a person just saying hello to you";}
}
And finally the important Class:
public Class PoshPerson: Person
{
public String SayHello() { return "Hey, I'm too posh to say hello to you";}
}
My first question is would the following code collect the method of PoshClass or Person Class?
public delegate String Collector();
event Collector CollectorEvent;
void GetMethod(CanSayHello c){CollectorEvent += c.SayHello;}
**GetMethod(new PoshPerson());**
If it will collect the method from Person class, I guess that I should declare the method at Person as virtual and the method at PoshPerson override.
I would really like that the two method signatures were equal. Is it possible in any way?
Your example runs
Person‘s method. If you changePoshPersontoPoshPerson : Person, CanSayHello(which you might think would change nothing, sincePerson : CanSayHello), it runsPoshPerson‘s method.I agree with @millimoose: “I’d avoid method hiding whenever possible, precisely because compile-time polymorphism is not very intuitive.” I would recommend that you change
Person.SayHellotovirtual, andPoshPerson.SayHellotooverride. That way regardless of whether you know of the instance as aCanSayHello,Person, orPoshPerson, the current instance type’s method runs.