1

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?

Padrus
  • 2,013
  • 1
  • 24
  • 37

2 Answers2

6

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
    }
}
poke
  • 369,085
  • 72
  • 557
  • 602
  • Thanks, I corrected the errors I made in my example as my current situation was `public new void MethodB()` – Padrus Nov 20 '14 at 13:20
0
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

nim
  • 357
  • 1
  • 5
  • 16