0

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

3 Answers3

2

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
}
David
  • 208,112
  • 36
  • 198
  • 279
  • Is there any way I can use this and also force the subclass to create an overridden version of the BaseClass method? (Like what would happen if BaseClass.Edit() was marked as abstract) – Bloody Solomon Sep 27 '22 at 17:55
  • @BloodySolomon: Not that I'm immediately aware of. [This](https://stackoverflow.com/q/2118055/328193) looks like a good place to learn more about that. – David Sep 27 '22 at 17:57
1

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.

Jonathan Wood
  • 65,341
  • 71
  • 269
  • 466
0
public class BaseClass
{
    public virtual void Edit(){
        // Some common functionality goes here
    }    
}

public class SubClass : BaseClass
{
    public override void Edit(){
        base.Edit();
    }
}
burning_LEGION
  • 13,246
  • 8
  • 40
  • 52