Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# inheritance and method signatures

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.

like image 860
Mike Avatar asked Oct 04 '22 18:10

Mike


1 Answers

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)
like image 171
Shaun McCarthy Avatar answered Oct 07 '22 22:10

Shaun McCarthy