Padrus
Padrus

Reputation: 2053

C# heritage : Call child method from parent method called by child

I'm facing a problem here, let's assume I have a parent class :

class ParentClass 
{
    public void MethodA()
    {
        //Do stuff
        MethodB();
    }

    public void MethodB()
    {
        //Do stuff
    }
}

A child class inheriting ParentClass and overriding MethodB() :

class ChildClass : ParentClass
{
    public new void MethodB()
    {
        //Do stuff
    }
}

Now, if I call MethodA() from a ChildClass object

public static void Main()
{
    ChildClass childObject = new ChildClass();
    childObject.MethodA();
}

How can I be sure that the MethodB() hat will be called will be the one from the child class?

Upvotes: 1

Views: 1871

Answers (2)

nim
nim

Reputation: 328

using System;

namespace ConsoleApplication6
{
    class Program
    {
        static void Main(string[] args)
        {
            var childObject = new ChildClass();

            childObject.MethodA();
            childObject.MethodB();
            childObject.MethodC();

            Console.ReadLine();
        }
    }

    class ParentClass 
    {
        public void MethodA()
        {
            //Do stuff
            _MethodB();
        }

        private void _MethodB()
        {
            Console.WriteLine("[B] I am called from parent.");
        }

        public virtual void MethodB()
        {
            _MethodB();
        }

        public void MethodC()
        {
            Console.WriteLine("[C] I am called from parent.");
        }
    }

    class ChildClass : ParentClass
    {
        public override void MethodB()
        {
            Console.WriteLine("[B] I am called from chield.");
        }

        public new void MethodC()
        {
            Console.WriteLine("[C] I am called from chield.");
        }
    }
}

enter image description here

Upvotes: 0

poke
poke

Reputation: 387647

If you fix the compile errors, by making the method virtual in the parent class, and by adding a return value to the method in the child class, then it will work just fine:

class ParentClass 
{
    …

    public virtual void MethodB()
    {
        //Do stuff
    }
}
class ChildClass : ParentClass
{
    public override void MethodB()
    {
        //Do stuff
    }
}

Upvotes: 6

Related Questions