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.
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);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With