Interesting observation on C# 4’s optional parameter

The oth­er day I had an inter­est­ing obser­va­tion on the option­al para­me­ters in C# 4, where­by if you spec­i­fy a para­me­ter as option­al on an inter­face you don’t actu­al­ly have to make that para­me­ter option­al on any imple­ment­ing class:

   1: public interface MyInterface

   2: {

   3:     void TestMethod(bool flag=false);

   4: }

   5:

   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 inter­change­ably:

   1: var obj = new MyClass();

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

   3:

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

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

Nat­u­ral­ly, this bags the ques­tion of why the com­pil­er doesn’t enforce the imple­men­ta­tion to match the default val­ue spec­i­fied by the con­tract?

Luck­i­ly, my sub­se­quent ques­tion on SO was answered by Eric Lip­pert from the C# com­pil­er 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­pil­er does it dif­fer­ent­ly.

References:

My ques­tion on Stack­Over­flow

Arti­cle on pos­i­tives and pit­falls of using option­al para­me­ters