5

Why is the output B5, can someone explain?

class A
{
       public virtual void M(int x=5)
       Console.Write("A"+x);
}

class B:A
{
       public override void M(int x=6)
       Console.Write("B"+x);

}
class Program
{
       static void Main(string[] args)
        {
            A a = new B();
            a.M();
        }
}
//Output is : B5

I expect the output to be B6, but the actual output is B5.

  • 2
    Possible duplicate of [C# optional parameters on overridden methods](https://stackoverflow.com/questions/8909811/c-sharp-optional-parameters-on-overridden-methods) – Fabjan Sep 19 '19 at 09:20
  • 1
    Also this: [Can you explain me this strange behaviour of c# with optional arguments?](https://stackoverflow.com/questions/9569140/can-you-explain-me-this-strange-behaviour-of-c-sharp-with-optional-arguments) – Fabjan Sep 19 '19 at 09:24
  • Is it a compiler bug? I debug the code in VS2017 with breakpoint on B.M() called as expected but x is really 5 as the method signature indicates 6... There is a polymorphism break with default parameters values. The compiler should at least indicates a warning when the default value is changed or use it as expected. –  Sep 19 '19 at 10:24
  • Yeah, that's the question: is it a bug or there is some meaning behind this behavior. The explanation is very simple but my question is why it's working like that. Hope someone could answer this question. – David Mosyan Sep 19 '19 at 10:48

1 Answers1

6

Default parameters don't work as you expect them. They are constants that are hard-wired into method call during compilation. And during compilation, only known type is that of A.

Your code is equivalent to:

   static void Main(string[] args)
    {
        A a = new B();
        a.M(5);
    }
Euphoric
  • 12,645
  • 1
  • 30
  • 44
  • Thanks for the answer. Could you please provide more details about this? Why this happens and is this normal, or it more accurate to print the default value for the Derived class? Thanks in advance – David Mosyan Sep 19 '19 at 09:19