Question

public interface IFoo
{
    void Foo(bool flag = true);
}

public class Test : IFoo
{
    void IFoo.Foo(bool flag = true) //here compiler generates a warning
    {

    }
}

The warning says that the given default value will be ignored as it is used in the context which does not allow it.

Why are optional parameters not allowed for explicitly implemented interfaces?

Was it helpful?

Solution

Explicitly implemented interface methods are always called with a target whose compile-time type is the interface, not an specific implementation. The compiler looks at the optional parameters declare by the method it "knows" it's invoking. How would you expect it to know to take the parameters from Test.Foo when it only knows of the target expression as type IFoo?

IFoo x = new Test();
x.Foo(); // How would the compiler know to look at the Test.Foo declaration here?

OTHER TIPS

I would use method overloading.

public interface IFoo
{
    void Foo(bool flag);
    void Foo();
}

public class Test : IFoo
{
    void Foo() {
        this.Foo(true);
    }

    void Foo(bool flag) {
         // Your stuff here.
    }
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top