Inheritance

capri

Active member
Joined
Jun 16, 2015
Messages
42
Programming Experience
5-10
Hi,


I have a class A that inherits another class B and calls a method in Class B. That method in turn calls another method which is overridable in Class B. Now, I want the inner method to be created in the calling Class A. But I noticed that the control comes to the first method in Class B and then goes to the inner method in Class B itself. Is it possible to bypass that inner method and call my overrided method instead?


Thanks
 
I have a class A that inherits another class B and calls a method in Class B.

Are you saying that A calls that method on itself or that it creates an instance of B and calls it on that? If it's the latter then the inheritance part becomes irrelevant. If it's the former then it should already work as you expect so you must have done something wrong. This is how it should look:
using System;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            var a = new A();
            var b = new B();

            a.DoSomething();
            b.OuterMethod();

            Console.ReadLine();
        }
    }

    class B
    {
        public void OuterMethod()
        {
            InnerMethod();
        }

        public virtual void InnerMethod()
        {
            Console.WriteLine("B.InnerMethod");
        }
    }

    class A : B
    {
        public void DoSomething()
        {
            OuterMethod();
        }

        public override void InnerMethod()
        {
            Console.WriteLine("A.InnerMethod");
        }
    }
}
Try running that code and you'll see that it works as expected.
 
Back
Top Bottom