Consider the following console application:
class Program
{
static void Main()
{
MyInterface test = new MyClass();
test.MyMethod();
Console.ReadKey();
}
}
interface MyInterface
{
void MyMethod(string myString = "I am the default value on the interface");
}
class MyClass : MyInterface
{
public void MyMethod(string myString = "I am the default value set on the implementing class")
{
Console.WriteLine(myString);
}
}
The output from this program is:
I am the default value on the interface
(1) Why isn't there a way of specifying a parameter as optional on an interface without supplying a value. I consider the default value to be implementation detail. If we wrote this code in the pre-optional parameter style we would create two overloads in the interface and the default value would be specified in the implementing class. I.e. we would have:
interface MyInterface
{
void MyMethod();
void MyMethod(string myString);
}
class MyClass : MyInterface
{
public void MyMethod()
{
MyMethod("I am the default value set on the implementing class");
}
public void MyMethod(string myString)
{
Console.WriteLine(myString);
}
}
Which outputs as we would expect,
I am the default value set on the implementing class
(2) Why can't we override the default value in the implementing class!