I am working on a class that needs run a different process method based on the type of object I pass in. I thought that overloading might work here, but I have a question. Lets say I have two interfaces:
public interface IEmail
{
Some properties ...
}
and
public interface ISpecialEmail : IEmail
{
Some more properties....
}
and a class to process these objects:
public class EmailProcessor
{
public void ProcessEmail (IEmail email)
{
do stuff;
}
public void ProcessEmail (ISpecialEmail email)
{
do different stuff
}
}
My question is, being that ISpecialEmail inherits from IEmail, are these method signatures sufficiently different to allow for overloading? My original thought is that ISpecialEmail emails would also trigger the IEmail signature because technically that interface is implemented also.
Thanks for your help.
It depends on how you call the methods.
For example, assume you have Email : IEmail
and SpecialEmail : ISpecialEmail
. If you declared a list of emails:
List<IEmail> emails = new List<IEmail> {new Email(), new SpecialEmail()};
And then ran
foreach (var email in emails) { EmailProcessor.ProcessEmail(email) }
It will call public void ProcessEmail (IEmail email)
for both - because the call binding happens at compile time (i.e. it wouldn't work the way you wanted).
It would also fail if you did something like:
var email = GetEmail(); // returns either IEmail or IExtendedEmail
EmailProcessor.ProcessEmail(email); // Would ONLY call ProcessEmail(IEmail)
So, polymorphism would fail with those signatures.
However, the following would work:
var email = GetEmail(); // returns only IEmail
var extendedEmail = GetExtendedEmail(); // returns only IExtendedEmail
EmailProcessor.ProcessEmail(email); // Would all ProcessEmail(IEmail)
EmailProcessor.ProcessEmail(extendedEmail ); // Would call ProcessEmail(IExtendedEmail)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With