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?

2
  • Why would it need to reject it? Commented Jul 3, 2014 at 12:07
  • I suppose I considered optional arguments to be part of the method signature, but looking at the related questions that have been posted, it seems that isn't the case. Commented Jul 3, 2014 at 12:10

2 Answers 2

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") 
Sign up to request clarification or add additional context in comments.

Comments

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

1 Comment

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.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.