2

I have a parent class with many methods in it that are all called by a single top-level method.

Conceptually the parent class looks like this:

class ParentClass
{
    void TopMethod(){ Lots of code and calls Methods1-N defined below}

    void Method1(){}
    void Method2(){}
    ...
    void MethodN(){}
}

I have many other classes that I want to be just minor variations on this base class. So I declare them as inheriting from ParentClass. Say all I need to do is change the definition of Method1 in the Child Classes. But how do I tell the child class to use everything else from the ParentClass, just with the new definition for Method1. In particular I don’t want the duplicate code of overriding TopMethod in the child class just so I can make it use the redefined Method1 in the child class instead of the Method1 in the ParentClass.

John B
  • 51
  • 4
  • Well if Method1, Method2 etc are all virtual, you just override Method1 in the derived class... – Jon Skeet Feb 28 '19 at 15:49
  • You make your method virtual in parent class and override them in inherited classes wherever needed – Haseeb Asif Feb 28 '19 at 15:50
  • 1
    Also consider the appropriate access modifiers on your members (methods in this case). In your example code everything is `private` by default which means a base class could not see those members (or override them). If you want access inside a derived class to a member of the base class you need `protected` at a minimum. If you want to define a new implementation it needs to also be marked as `virtual`. – Igor Feb 28 '19 at 15:52
  • See also [What are Virtual Methods?](https://stackoverflow.com/q/622132/1260204) and [What is the difference between an abstract function and a virtual function?](https://stackoverflow.com/q/391483/1260204) and [Practical usage of virtual functions in c#](https://stackoverflow.com/q/1062102/1260204) – Igor Feb 28 '19 at 15:53
  • The post by DavidG is what I was trying to do - thanks! I was using just the "new" keyword in the child class, instead of "virtual" in the parent and "override" in the child. – John B Feb 28 '19 at 16:24

2 Answers2

1

From the docs: virtual keyword

Schwarzie2478
  • 2,186
  • 26
  • 30
1

You need to make Method1, Method2 etc. virtual and override them in the child class. For example:

public class ParentClass
{
    public void TopMethod()
    {
        Console.WriteLine("Top method in parent");
        Method1();
    }

    public virtual void Method1()
    {
        Console.WriteLine("Method1 in parent");
    }
}

public class ChildClass : ParentClass
{
    public override void Method1()
    {
        Console.WriteLine("Method1 in child");
    }
}

Now calling each class:

var parent = new ParentClass();
var child = new ChildClass();

parent.TopMethod();
child.TopMethod();

Will give you this output:

Top method in parent
Method1 in parent
Top method in parent
Method1 in child
DavidG
  • 113,891
  • 12
  • 217
  • 223