horgh
horgh

Reputation: 18534

Optional parameters in explicitly implemented interfaces

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?

Upvotes: 3

Views: 448

Answers (2)

Simon Germain
Simon Germain

Reputation: 6844

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.
    }
}

Upvotes: 0

Jon Skeet
Jon Skeet

Reputation: 1500175

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?

Upvotes: 2

Related Questions