I'm supporting some code that has optional parameters and interfaces.
As a simplified example: I have a default of 2 in the interface, and 1 in the implementation class.
public interface IOptionalInterface
{
int Get(int x = 2);
}
public class ClassX : IOptionalInterface
{
public int Get(int x = 1)
{
return x;
}
}
This code passes, as I expected.
Assert.AreEqual(new ClassX().Get(), 1);
However, when I pass the class back as the interface, and invoke it later, I get the optional parameter from the interface; which surprised me.
private IOptionalInterface Build()
{
return new ClassX();
}
public void Expect1()
{
var y = Build();
Assert.AreEqual(y.Get(), 1); // fails, it returns 2.
}
What are the major design considerations that I'm missing that make this preferential?
Is there a clean way to assure the implementing class gets to set the default value?