Warning From Explicitly Implementing an Interface with Optional Parameters

The compiler is telling you

void ITestInterface.TestOptional(int a = 5, int b = 5, object c = null)

Is fundamentally the same as

void ITestInterface.TestOptional(int a, int b, object c)

The reason being, since you have to invoke TestOptional through the interface the interface will supply the parameters. There is no way at the class for you to have not been supplied a parameter value.

2020 edit: soon you will be able to do this with C# 8 by default implementations of interfaces

interface ILogger
{
    void Log(LogLevel level, string message);
    void Log(Exception ex) => Log(LogLevel.Error, ex.ToString());
}

You could just as easily do something akin to:

public interface ITestInterface
{
     void TestOptional(int a, int b, object c);

     void TestOptional() => TestOptional(5);
     void TestOptional(int a) => TestOptional(a, 10)
     void TestOptional(int a, int b) => TestOptional(a, b, null);

}

The problem with optional arguments in C# is whether the callee sees the object as a TestClass or an ITestInterface. In the first case, the values declared in the class apply. In the second case the values declared in the interface apply. It is because the compiler uses the statically available type information to construct the call. In case of an explicit interface implementation the method is never called 'for a class', always 'for an interface'

The C# Language Specification in 10.6.1 states:

If optional parameters occur in an implementing partial method declaration (§10.2.7) , an explicit interface member implementation (§13.4.1) or in a single-parameter indexer declaration (§10.9) the compiler should give a warning, since these members can never be invoked in a way that permits arguments to be omitted.


Craig,

These warnings are coming from the default values specified in class method implementation. In .net, the default value for the argument is always determined by the reference type. And of course, with an explicit interface implementation like this it is only possible to call this method via an interface reference - which defines the default value. As such it's of course irrelevant what value you put here in the class, since it'll never ever be resolved and you can remove it happily. Intellisense will be fine, given that the default value here can never ever be effective.

http://funcakes.posterous.com/?tag=c

http://funcakes.posterous.com/c-40-optional-parameters-default-values-and-i