0

I just have one basic question :

in below code returns only derived class methods but i don't know why . kindly help to find out the problem.

class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("Hello World!");
            A value = new B();
            value.method();
            Console.Read();
        }
    }
    class A
    {
        public void method()
        {
            Console.WriteLine("A");
        }
    }
    class B : A
    {
        public void method()
        {
            Console.WriteLine("B");
        }
    }
mohanasundaram p
  • 63
  • 1
  • 1
  • 6

1 Answers1

1

When you don´t explicitely add any modifier (like virtual or override) a new is implictely added into the code, which yields to the following:

class B : A
{
    public new void method()
    {
        Console.WriteLine("B");
    }
}

This hides the base-implemenation, but only if your reference is of type B. In your case you have a reference of the base-type A, which has no clue on the new member and thus will allways perform a call to the base-class member

I don´t know why you don´t have virtual and override here. If it´s really not possible for you to add them, you need a reference of the derived type:

B value = new B();
value.method();
MakePeaceGreatAgain
  • 35,491
  • 6
  • 60
  • 111
  • I think he is asking "why", instead of "how to get it done". Though he create an "new B();" but method from "A class" is called. again why ? – Kumaran Raj K Jun 04 '19 at 12:02
  • @KumaranRajK I repeat myself: "This hides the base-implemenation, but only if your reference is of type B". Doesn´t this explain the why-part? – MakePeaceGreatAgain Jun 04 '19 at 12:08