Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why the output default value is from Base class?

Tags:

c#

.net

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.

like image 525
David Mosyan Avatar asked Sep 19 '19 09:09

David Mosyan


1 Answers

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);
    }
like image 143
Euphoric Avatar answered Sep 29 '22 19:09

Euphoric