-1

could you please tell me why the result of the code below is BaseClass::method? I was thinking that DerivedClass2 will just override the virtual method of DerivedClass1 which is declared as new, meaning that the BaseClass method is not used. Or since the DerivedClass2 overrides a virtual method of DerivedClass1, then there's dynamic binding which will call the DerivedClass2 method version and not the one of DerivedClass1 or BaseClass. Any help? What's wrong with my reasoning? thanks

class BaseClass
    {
        public void method() { Console.WriteLine("BaseClass::method"); }
    }
    class DerivedClass1 : BaseClass
    {
        public new virtual void method() { Console.WriteLine("DerivedClass1::method"); }
    }
    class DerivedClass2 : DerivedClass1
    {
        public override void method(){ Console.WriteLine("DerivedClass2::method"); }
    }
    class Program
    {
        static void Main(string[] args)
        {    
            BaseClass e = new DerivedClass2();
            e.method();//BaseClass::method. But Why???

            Console.ReadLine();
        }
    }
Dave ddd
  • 117
  • 9

3 Answers3

0

You're calling a non-virtual method of BaseClass.

That is the method that will be called, regardless of whether derived classes add other methods.

SLaks
  • 868,454
  • 176
  • 1,908
  • 1,964
  • but DerivedClass2 inherits the method from DerivedClass1. And DerivedClass1 has already defined it's own new method using the keyword "new", isn't it? – Dave ddd Oct 25 '15 at 16:51
  • @Daveddd: Yes, but that isn't the method you're calling. The whole point of `new` is that it _doesn't_ do runtime dynamic dispatch. – SLaks Oct 25 '15 at 16:52
  • You're calling explicitly the base class method, if you cast to DerivedClass1 the result will be different or to DerivedClass2 – kirotab Oct 25 '15 at 16:53
  • what do you mean by "that isn't the method you're calling"? – Dave ddd Oct 25 '15 at 16:54
  • @Daveddd: At compile time, you're calling `BaseClass.method`, which is not virtual. – SLaks Oct 25 '15 at 16:54
0

The BaseClass.method() is not virtual. It is hidden by a virtual method in DerivedClass1, which is then overriden in DerivedClass2.

The type of the variable e is BaseClass, and that's what the compiler uses to find the method to call. The only option is the non-virtual BaseClass.method(). If you change the type of the variable to DerivedClass1, the compiler will resolve the call to the virtual new DerivedClass1.method(). At run-time the DerivedClass2.method() will be called.

Don't expect polymorphic behavior when you hide methods with the new modifier.

Jakub Lortz
  • 14,616
  • 3
  • 25
  • 39
0

Because in this line:

BaseClass e = new DerivedClass2(); 

e acts like BaseClass object. So it calls BaseClass.method.

It is like you wrote:

DerivedClass2 e = new DerivedClass2();
((BaseClass)e).method();

You have to read more and understand about Inheritance and Polymorphism.

shadow
  • 1,883
  • 1
  • 16
  • 24