Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 954
horgh Avatar asked Mar 02 '26 22:03

horgh


1 Answers

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?
like image 61
Jon Skeet Avatar answered Mar 04 '26 11:03

Jon Skeet



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!