Interesting observation on C# 4’s optional parameter

The other day I had an inter­est­ing obser­va­tion on the optional para­me­ters in C# 4, whereby if you spec­ify a para­me­ter as optional on an inter­face you don’t actu­ally have to make that para­me­ter optional on any imple­ment­ing class:

   1: public interface MyInterface

   2: {

   3:     void TestMethod(bool flag=false);

   4: }


   6: public class MyClass : MyInterface

   7: {

   8:     public void TestMethod(bool flag)

   9:     {

  10:         Console.WriteLine(flag);

  11:     }

  12: }

Which means you won’t be able to use the imple­ment­ing class and the inter­face interchangeably:

   1: var obj = new MyClass();

   2: obj.TestMethod(); // compiler error


   4: var obj2 = new MyClass() as MyInterface;

   5: obj2.TestMethod(); // prints false

Nat­u­rally, this bags the ques­tion of why the com­piler doesn’t enforce the imple­men­ta­tion to match the default value spec­i­fied by the contract?

Luck­ily, my sub­se­quent ques­tion on SO was answered by Eric Lip­pert from the C# com­piler team, not to waste time and effort repeat­ing what’s already been said, check out his answer and it’s clear to see the ratio­nale here and why it would be imprac­ti­cal and incon­ve­nient should the com­piler does it differently.


My ques­tion on StackOverflow

Arti­cle on pos­i­tives and pit­falls of using optional parameters