Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Raise event of object where the type implements an Interface

I have a problem when trying to raise an event of an object where the type implements an interface (where the event is) form another class.

Here is my code :

The interface IBaseForm

public interface IBaseForm
{
    event EventHandler AfterValidation;
}

The Form that implement the interface IBaseForm

public partial class ContactForm : IBaseForm
{
    //Code ...

    public event EventHandler AfterValidation;
}

My controller : Here where the error occurs

Error message :

The event AfterValidation can only appear on the left hand side of += or -=(except when used from whithin the type IBaseForm)

public class MyController
{
    public IBaseForm CurrentForm { get; set; }

    protected void Validation()
    {
        //Code ....

        //Here where the error occurs
        if(CurrentForm.AfterValidation != null)
            CurrentForm.AfterValidation(this, new EventArgs());
    }
}

Thanks in advance

like image 487
SidAhmed Avatar asked Dec 13 '25 04:12

SidAhmed


1 Answers

You cannot raise an event from outside of the defining class.

You need to create a Raise() method on your interface:

public interface IBaseForm
{
    event EventHandler AfterValidation;

    void RaiseAfterValidation();
}

public class ContactForm : IBaseForm
{
    public event EventHandler AfterValidation;

    public void RaiseAfterValidation()
    {
        if (AfterValidation != null)
            AfterValidation(this, new EventArgs());
    }
}

And in your controller:

protected void Validation()
{
    CurrentForm.RaiseAfterValidation();
}

But it is usually a design smell if you want to trigger an event from outside the defining class... usually there should be some logic in the IBaseForm implementations which triggers the event.

like image 66
nemesv Avatar answered Dec 15 '25 17:12

nemesv