Prankster
Prankster

Reputation: 4079

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

?

Upvotes: 9

Views: 501

Answers (5)

bdukes
bdukes

Reputation: 155925

You're making the Print method private, so the only available Print method is the inherited one.

Upvotes: 5

Joel Coehoorn
Joel Coehoorn

Reputation: 415705

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.

Upvotes: 20

Lennaert
Lennaert

Reputation: 2465

Externally, the new B.Print()-method isn't visible anymore, so A.Print() is called.

Within the class, though, the new B.Print-method is still visible, so that's the one that is called by methods in the same class.

Upvotes: 3

samjudson
samjudson

Reputation: 56853

Without the public keyword then the method is private, therefore cannot be called by Main().

However the Print2() method can call it as it can see other methods of its own class, even if private.

Upvotes: 1

Raj
Raj

Reputation: 6830

when you remove the keyword public from class b, the new print method is no longer available outside the class, and so when you do b.print from your main program, it actually makes a call to the public method available in A (because b inherits a and a still has Print as public)

Upvotes: 2

Related Questions