Home > other >  C# Method Override & Inherit Base Functionality
C# Method Override & Inherit Base Functionality

Time:09-28

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
    }
}

CodePudding user response:

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
}

CodePudding user response:

Other answers have shown how to call Edit() in the base class. But, depending on your needs, here's another pattern that might work.

public class BaseClass
{
    public virtual void Edit()
    {
        // Common functionality here
        OnEdit();
    }

    protected virtual void OnEdit() {}
    

}

public class SubClass : BaseClass
{
    public override void OnEdit()
    {
        // Specialized functionality here
    }
}

Here, the Edit() function only exists in BaseClass. But you can add subsequent functionality by overriding OnEdit().

This is an advantage if Edit() must always be implemented. It works even if you don't add custom functionality (override OnEdit()). But you can override it as needed.

And if you want to require that OnEdit() is always overridden, just make it abstract instead of virtual.

CodePudding user response:

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

public class SubClass : BaseClass
{
    public override void Edit(){
        base.Edit();
    }
}
  • Related