2

I recently encountered the following behaviour;

internal interface IOptionalParamTest
{
    void PrintMessage(string message = "Hello");
}

class OptionalParamTest : IOptionalParamTest
{
    public void PrintMessage(string message = "Goodbye")
    {
        Console.WriteLine(message);
    }
}

internal class Program
{
    static void Main()
    {
        IOptionalParamTest usingInterface = new OptionalParamTest();
        usingInterface.PrintMessage(); // prints "Hello"

        OptionalParamTest usingConcrete = new OptionalParamTest();
        usingConcrete.PrintMessage();// prints "Goodbye"
    }
}

My question is; why does the compiler not reject the implementation of PrintMessage with a different default value from that defined on the interface?

Chris McAtackney
  • 5,192
  • 8
  • 45
  • 69

2 Answers2

3

The call PrintMessage(); is just syntactic sugar. There is no method PrintMessage() that takes zero parameters. The compiler simply inserts the correct value. So, the compiler changes the first call to:

PrintMessage("Hello");

because the compile-time type of usingInterface is IOptionalParamTest.

The compile-time type of usingConcrete is OptionalParamTest, so it looks there for the value to insert and the call becomes

PrintMessage("Goodbye")
Dennis_E
  • 8,751
  • 23
  • 29
1

Interface implementations simply don't use default values (rather: it is only the call-site that uses the default values); it is allowed on regular method declarations, so that you can still use the default parameter value feature - but there is no requirement for it to be the same value. If we add an explicit interface implementation, it becomes more interesting:

void IOptionalParamTest.PrintMessage(string message = "what happens here?")
{
    Console.WriteLine(message);
}

And in answer to the question "what happens here?": a compiler warning:

The default value specified for parameter 'message' will have no effect because it applies to a member that is used in contexts that do not allow optional arguments

Marc Gravell
  • 1,026,079
  • 266
  • 2,566
  • 2,900
  • Hm, interesting warning message. In my particular scenario, I've decided to just make the argument non-optional to remove the lack of clarity on what is expected to happen. – Chris McAtackney Jul 03 '14 at 12:46