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. Conver
The reason for doing so would be to make it easier for callers to use when the compile-time type they have is just the interface:
public void Foo(IService1 service)
{
service.MyMethod("Text"); // Calls MyMethod("Text", false)
}
It's fairly common for a caller to only know about the interface something implements rather than the concrete type - so if you believe optional parameters are a good idea at all (it's controversial) it makes as much sense to have them on interfaces as on concrete types.
If one is designing an interface with a method Foo
that takes parameter Bar
, and 99% (but not 100%) of calls to Foo
pass zero for Bar
, one must either:
Option #3 seems most convenient to me when it's workable.
Example:
public interface IService1
{
void MyMethod(string text, bool flag = true);
}
public class MyService1a : IService1
{
public void MyMethod(string text, bool flag) { }
}
Usage:
IService1 ser = new MyService1a();
ser.MyMethod("A");
2nd parameter passed to MyService1a
will be true
, as default parameter in interface.
Interface designer's assumption of default parameters may be different then implementer's design.
Default parameters are simply expanded by compiler and parameters are replaced by actual default values.
When you call method on an object that is an instance of an interface, then compiler will replace default values specified on the interface.
And when you call method on an object that is an instance of class, then compiler will replace default values specified on the class.
It is useful in that the interface can declare them the way it wants, so you get the exact flexibility that you wanted when making the interface. In other words, an implementer in a derived class can make the parameter optional, can make it required, etc. as desired. If it isn't optional, the derived classes must have it.
Your example above shows just that -- flexibility in the derived classes.