Why the following program prints
B
B
(as it should)
public class A
{
public void Print()
{
Console.WriteLine("A");
}
}
public class B : A
{
public new void Print()
{
Console.WriteLine("B");
}
public void Print2()
{
Print();
}
}
class Program
{
static void Main(string[] args)
{
var b = new B();
b.Print();
b.Print2();
}
}
but if we remove keyword 'public' in class B like so:
new void Print()
{
Console.WriteLine("B");
}
it starts printing
A
B
?
When you remove the public
access modifier, you remove any ability to call B's new Print()
method from the Main
function because it now defaults to private
. It's no longer accessible to Main.
The only remaining option is to fall back to the method inherited from A, as that is the only accessible implementation. If you were to call Print() from within another B method you would get the B implementation, because members of B would see the private implementation.
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