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.
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);
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With