Darren Darren - 8 days ago 6
C# Question

How to blindly raise an event in a base class without calling it from the derived class

Given the following abstract class and a derived class:

public abstract class Worker{
public bool DoingWork {get;set;}
public abstract void DoWork();
}

public class MyWorker : Worker{

public override void DoWork(){
// do all the work in here..
// currently setting the base classes DoingWork property at the start and end of work
}
}


Is there a mechanism that would allow me to raise an event in the
abstract
when an implemented
DoWork()
method is called, without having to code the derived class to implement or call any additional methods.

The reason for the question is that I would like to raise an event when any of the implemented
DoWork()
are called, and finished and removing the need for the implementations to set any flag in the base class.

Answer

If the caller is calling the derived class's method, no. If you want the base class to control what's going on you'll want to have the consumer calling a base class method, and then simply have the derived class override the behavior that you want without making that the method that the caller calls by making the overridden method protected.

public abstract class Worker
{
    public bool DoingWork { get; set; }
    private event Action WorkCompleted; 
    public void DoWork()
    {
        DoingWork = true;
        DoWorkImplementation();
        DoingWork = false;
        WorkCompleted?.Invoke();
    }
    protected abstract void DoWorkImplementation();
}

public class MyWorker : Worker
{
    protected override void DoWorkImplementation()
    {
        Console.WriteLine("Hello World!");
    }
}