Is there any reason to declare optional parameters in an interface?

Viewed 18165

You can declare optional parameters in an interface method but implementing classes are not required to declare the parameters as optional, as Eric Lippert explained. Conversely, you can declare a parameter as optional in an implementing class but not in the interface.

So is there any reason to declare optional parameters in an interface? If not, why is it allowed?

Examples:

public interface IService1
{
    void MyMethod(string text, bool flag = false);
}

public class MyService1a : IService1
{
    public void MyMethod(string text, bool flag) {}
}

public class MyService1b : IService1
{
    public void MyMethod(string text, bool flag = true) { }
}

public interface IService2
{
    void MyMethod(string text, bool flag);
}

public class MyService2b : IService2
{
    public void MyMethod(string text, bool flag = false) { }
}
6 Answers

I don't think you should mainly because interfaces are not meant to handle matters of state but matters of function. Classes themselves are supposed to handle matters of state and defining properties as well as what is done by those classes (I consider an optional parameter a subtle definition of state). The catch is on the declaration and use of an object by appealing to its interface or its class. Example:

public interface IFoo
{
    void Bar(int i, int j);
}

public class Foo : IFoo
{
    public void Bar(int i, int j = 0)
    {
        Console.WriteLine(i);
        Console.WriteLine(j);
    }
}

class Program
{
    static void Main(string[] args)
    {
        //referring to interface requires second arg
        IFoo foo = new Foo();
        foo.Bar(1);

        //allows one arg and uses optional arg
        Foo foo = new Foo();
        foo.Bar(1);
    }
}

Essentially the functionality resorts to the type the object is encapsulated in with the corresponding requirements for that class or interface applying on the object. If the interface requires it also requires (for it is functioning like the interface) where if the interface did NOT require it it would ALSO not require it (functioning like the interface). You have to ask yourself though whether the interface or implementing/inheriting objects are structured correctly, but then again the flexibility of having a default value for the interface is not a hard and fast rule against.

Related