Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# interface - implement with different signature

Tags:

c#

interface

I suppose this is somewhat of a design question too. Is it possible to override a method from an interface when the overriding signature has a different signature type?

For example, lets say that I want two different classes that should have the following:

 interface IProtocolClient
 {
    void connect(Type1 t1, Type2 t2, Type3 t3);
 }

Would it be possible to impelemt the interfrace but have a different parameter set?

 class A : IProtocolClient {
   public void connect( Type1 t1, Type2 t2, Type3 t3 ) {}
 }

 class B : IProtocolClient {
   public void connect( Type1 t1, Type2 t2, Type3 t3, Type4 t4 ) {}
 }

Or should I approach this by creating a base class instead, and then create a wrapper method in class B such as:

 class B : IProtocolClient {
   public void connect( Type1 t1, Type2 t2, Type3 t3, Type4 t4)
   {
      // do what is needed with t4 to customize and then ...
      connect(t1,t2,t3);
   }

   public void connect( Type1 t1, Type2 t2, Type3 t3) {}
 }
like image 574
Dr. Watson Avatar asked Dec 21 '22 13:12

Dr. Watson


2 Answers

An Interface is a 'contract' that your class 'signs up to' and the class must implement the interface as defined. Your second approach to use a class specific method that extends the interface specified class and then calls the interface method is a reasonable solution but of course does mean that you can't use the Interface as a type which could defeat the purpose.

like image 107
Lazarus Avatar answered Jan 05 '23 03:01

Lazarus


Your last option is the only one that would possibly work (as its the only option that properly implements the interface in both classes).

Remember, though, that anybody accessing the class via the interface will only have access to the connect(Type1 t1, Type2 t2, Type3 t3) method which completely voids the fact that you provide the other (unless people may access the type directly as well).

like image 31
Justin Niessner Avatar answered Jan 05 '23 05:01

Justin Niessner