What is really strange is that the value that you specify for an optional parameter in the interface really matters. I suppose you have a question if value is an interface detail or implementation. I would say the latter, but everything behaves like the first. For example, the following code outputs 1 0 2 5 3 7.
// Output: // 1 0 // 2 5 // 3 7 namespace ScrapCSConsole { using System; interface IMyTest { void MyTestMethod(int notOptional, int optional = 5); } interface IMyOtherTest { void MyTestMethod(int notOptional, int optional = 7); } class MyTest : IMyTest, IMyOtherTest { public void MyTestMethod(int notOptional, int optional = 0) { Console.WriteLine(string.Format("{0} {1}", notOptional, optional)); } } class Program { static void Main(string[] args) { MyTest myTest1 = new MyTest(); myTest1.MyTestMethod(1); IMyTest myTest2 = myTest1; myTest2.MyTestMethod(2); IMyOtherTest myTest3 = myTest1; myTest3.MyTestMethod(3); } } }
Interestingly, if your interface makes the parameter optional, then the class implementing it should not do the same:
// Optput: // 2 5 namespace ScrapCSConsole { using System; interface IMyTest { void MyTestMethod(int notOptional, int optional = 5); } class MyTest : IMyTest { public void MyTestMethod(int notOptional, int optional) { Console.WriteLine(string.Format("{0} {1}", notOptional, optional)); } } class Program { static void Main(string[] args) { MyTest myTest1 = new MyTest(); // The following line won't compile as it does not pass a required // parameter. //myTest1.MyTestMethod(1); IMyTest myTest2 = myTest1; myTest2.MyTestMethod(2); } } }
However, it seems a mistake that if you implement the interface explicitly, the value that you give in the class for the optional value will be meaningless. How can you use the value 9 in the following example?
// Optput: // 2 5 namespace ScrapCSConsole { using System; interface IMyTest { void MyTestMethod(int notOptional, int optional = 5); } class MyTest : IMyTest { void IMyTest.MyTestMethod(int notOptional, int optional = 9) { Console.WriteLine(string.Format("{0} {1}", notOptional, optional)); } } class Program { static void Main(string[] args) { MyTest myTest1 = new MyTest(); // The following line won't compile as MyTest method is not available // without first casting to IMyTest //myTest1.MyTestMethod(1); IMyTest myTest2 = new MyTest(); myTest2.MyTestMethod(2); } } }
Eric Lippert wrote an interesting series on this subject: additional arguments
Martin Brown Dec 19 '13 at 15:53 2013-12-19 15:53
source share