0

Consider this code:

public class A
{

    public void Method1()
    {
        Console.WriteLine("A.Method1");
    }
    public virtual void Method2()
    {
        Console.WriteLine("A.Method2");
    }
}
public class B : A
{
    public new void Method1()
    {
        Console.WriteLine("b.Method1");
    }

    public override void Method2()
    {
        Console.WriteLine("b.Method2");
    }
}

and this:

    B b = new B();
    b.Method1();
    b.Method2();
    Console.WriteLine("*********************");
    A a = b;
    a.Method1();
    a.Method2();

This is my Result:

b.Method1
b.Method2
A.Method1
b.Method2

My question is why when we call a.Method1() I get A.Method1 instead of getting b.Method1.And why method hiding not work.

Note This line:a = b

  • 1
    From [msdn](https://msdn.microsoft.com/en-us/library/aa691135(v=vs.71).aspx): *A declaration of a new member hides an inherited member only within the scope of the new member*. – Sinatr Jul 30 '15 at 07:40
  • 1
    Hiding you expected is known as **shadowing**. Many Q/A's are around, you can check [this one](http://stackoverflow.com/questions/392721/difference-between-shadowing-and-overriding-in-c). – miroxlav Jul 30 '15 at 07:45

2 Answers2

1

My question is why when we call a.Method1() I get A.Method1 instead of getting b.Method1. And why method hiding not work.

Because we call a regular, non-virtual method of class A. The new modifier does not change the behavior, it just suppresses the warning:

'...' hides inherited member '...'. Use the new keyword if hiding was intended.

See Knowing When to Use Override and New Keywords.

AlexD
  • 32,156
  • 3
  • 71
  • 65
0

The thing on the new keyword is that it works only if you create a reference of your derived type, namely B. But as you refer a reference of B to an object of type A the default-implementation is used instead. Having said this the following also works for your code:

A a = b;
((B)a).Method1();

Which leads to B.Method1 to be called.

However as Method2 within type A is virtual, the actual override B.Method2 is called.

MakePeaceGreatAgain
  • 35,491
  • 6
  • 60
  • 111