Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

public Event in abstract class

I have event declared in abstract class:

public abstract class AbstractClass
{
    public event Action ActionEvent;
}

public class MyClass : AbstractClass
{
    private void SomeMethod()
    {
        //Want to access ActionEvent-- Not able to do so
        if (ActionEvent != null)
        {
        }

    }
}

I wanted to access this base class event in derived. Further I wanted to access this event in some other derived class of MyClass:

MyClass.ActionEvent += DerivedMethod()

Please help me understand how to work with event defined in abstract classes.

like image 321
user421719 Avatar asked Apr 23 '15 18:04

user421719


1 Answers

An often used pattern for this is something like the below (you'll see a lot of it in the classes in the System.Windows.Forms namespace).

public abstract class MyClass
{
    public event EventHandler MyEvent;

    protected virtual void OnMyEvent(EventArgs e)
    {
        if (this.MyEvent != null)
        {
            this.MyEvent(this, e);
        }
    }
}

You would then use it in a derived class like this, optionally extending the behaviour:

public sealed class MyOtherClass : MyClass
{
    public int MyState { get; private set; }

    public void DoMyEvent(bool doSomething)
    {
        // Custom logic that does whatever you need to do
        if (doSomething)
        {
            OnMyEvent(EventArgs.Empty);
        }
    }

    protected override void OnMyEvent(EventArgs e)
    {
        // Do some custom logic, then call the base method
        this.MyState++;

        base.OnMyEvent(e);
    }
}
like image 167
Martin Costello Avatar answered Oct 12 '22 06:10

Martin Costello