Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How method hiding works in C#?

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

?

like image 674
Prankster Avatar asked Apr 02 '09 13:04

Prankster


1 Answers

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.

like image 173
Joel Coehoorn Avatar answered Sep 20 '22 09:09

Joel Coehoorn