[ACCEPTED]-Warning From Explicitly Implementing an Interface with Optional Parameters-optional-parameters

Accepted answer
Score: 27

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

The 9 C# Language Specification in 10.6.1 states:

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

Score: 23

The compiler is telling you

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

Is fundamentally 8 the same as

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

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

2020 edit: soon you will be able to do this 2 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 1 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);

Score: 3


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



More Related questions