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
publicaccess modifier, you remove any ability to call B’snew Print()method from theMainfunction because it now defaults toprivate. 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.