Search code examples
c#inheritanceoverriding

C# Method Override & Inherit Base Functionality


I'm still relatively new to C# so sorry if this is a dumb question. I am trying to make a multi-program application that will allow users to edit data from a database. Each application should have some common functionallity when the edit method is called (e.g. Toggle the application into edit mode). Is there any way that I can make subclasses of BaseClass run BaseClass.Edit() before running the contents of the overridden Edit() method?

public class BaseClass
{
    public void Edit(){
        // Some common functionality goes here
    }    
}

public class SubClass : BaseClass
{
    public void Edit(){
        // Do BaseClass.Edit() first...
        // Some more application specific functionality goes here
    }
}

Solution

  • Currently the SubClass is obscuring or hiding the BaseClass method. This generates a compiler warning because it's almost always not what was intended.

    Make the BaseClass method virtual:

    public virtual void Edit(){
        // Some common functionality goes here
    }
    

    And explicitly override it in the SubClass:

    public override void Edit(){
        // Do BaseClass.Edit() first...
        // Some more application specific functionality goes here
    }
    

    Then you can explicitly invoke the BaseClass method first:

    public override void Edit(){
        base.Edit();
        // Some more application specific functionality goes here
    }