How method hiding works in C#?
Asked Answered
A

5

8

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

?

Anatol answered 2/4, 2009 at 13:34 Comment(1)
good tricky scenario. thanks for sharing.Vanatta
L
20

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.

Leckie answered 2/4, 2009 at 13:37 Comment(0)
S
5

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

Sudarium answered 2/4, 2009 at 13:37 Comment(0)
K
3

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.

Krefetz answered 2/4, 2009 at 13:38 Comment(0)
C
2

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)

Cursorial answered 2/4, 2009 at 13:38 Comment(0)
B
1

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.

Bassinet answered 2/4, 2009 at 13:39 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.