Alex KeySmith
Alex KeySmith

Reputation: 17091

Optional arguments on interface and class can conflict

I have just come across an interesting gotcha where optional arguments on an interface and the implementing class can conflict.

I found this out the hard way (school boy error) whilst experimenting. You cannot spot it in the debugger and I assumed it was me messing up the dependency injection.

I'm guessing this is so an alternative interface can give a differing view on what default behaviour should be?

Is there a compiler warning or style cop rule to help point this out?

public interface MyInterface
{
    MyStuff Get(bool eagerLoad = true); //this overrules the implementation.

}

public class MyClass : MyInterface
{
    public MyStuff Get(bool eagerLoad = false) //will still be true
    {
        //stuff
    }           
}

Upvotes: 0

Views: 37

Answers (1)

Brian Rasmussen
Brian Rasmussen

Reputation: 116401

Remember default arguments are a compile-time feature. The compiler picks up the default argument based on the static type of the reference in question and inserts the appropriate default argument. I.e. if you reference is of the interface type you get one behavior but if the reference is of the class type you get the other in your case.

Upvotes: 1

Related Questions