Nick Bull
Nick Bull

Reputation: 9846

Interface methods with varying parameters

I have an interface as such:

public interface ICompleteable 
{
    public void Complete();
}

However, I want to extend classes with methods as such, with varying parameters:

public class CompleteableClassA : ICompleteable 
{
    public void Complete(string name) { ... }
}

public class CompleteableClassB : ICompleteable
{
    public void Complete(string email, string password) { ... }
}

What is a good way (or even better, a pattern?) to go about extending methods from interfaces with varying parameters?

Upvotes: 3

Views: 2330

Answers (3)

Hamlet Hakobyan
Hamlet Hakobyan

Reputation: 33381

If you plan to use same type of parameters you can use params

interface ICompleteable
{
    void Complete(params string[] parameters);
}

or, for vary types you can use

interface ICompleteable
{
    void Complete(params object[] parameters);
}

Upvotes: 0

Exceptyon
Exceptyon

Reputation: 1582

create a class that encapsulates the parameters, and extend that one if you want to:

public class CompleteParameters
{
  string parm1;
  // whatever you want
};

public class CompleteParametersTwo : CompleteParameters
{
  string parm2;
};


public interface ICompleteable 
{
    public void Complete(CompleteParameters parms);
}

Upvotes: 4

Tigran
Tigran

Reputation: 62248

You can not extend something that does not exist. So basically what you do here is just add new methods to every type, also those methods defer by definition from type to type, so there is no apparent common pattern that you may use in your interface.

You may think also about defining a base class, like :

public class Base {

   public void Complete(string name) { ... }
   public void Complete(string email, string password) { ... }
}

and after

public class CompleteableClassA : BaseClass, ICompleteable {
}

public class CompleteableClassB : BaseClass, ICompleteable {
}

In this case both classes share the same base class, so also share the same set of overloads of Complete(..) method.

Upvotes: 1

Related Questions