Search code examples
c#events.net-4.0raiseevent

Issue raising a simple event


My interface has an event that don't has an arguments

public interface IMyInterface
{
     event EventHandler OnSomethingHappened;
}

Here is how I am implementing it.

   public class MyBaseClass : IMyInterface
    {
private event EventHandler onSomethingHappened;
public event EventHandler OnSomethingHappened
{
    add
    {
        onSomethingHappened-= value;
        onSomethingHappened+= value;
    }

    remove
    {
        onSomethingHappened-= value;
    }
}
    }

But somehwere else when I try to use it as follows

if ( MyBaseClassInstance.OnSomethingHappened != null )
        MyBaseClassInstance.OnSomethingHappened();

I get following compilation error

The event 'ConsoleApplication1.IMyInterface.OnSomethingHappened' can only appear on the left hand side of += or -=

What am I doing wrong?


Solution

  • This is how your code might look:

        public interface IMyInterface
        {
            event EventHandler OnSomethingHappened;
        }
    
        //implement the interface
        public class MyBaseClass : IMyInterface
        {
            public event EventHandler OnSomethingHappened;
    
            public void DoSomeLogicWhichRaisesTheEvent()
            {
                if (OnSomethingHappened != null)
                {
                    MyBaseClass sender = this;
                    var eventArgs = new EventArgs();
                    //let all subscibers to event know that the event happened
                    OnSomethingHappened(sender, eventArgs);
                }
            }
        }
    
        public class ConsumerClass
        {
            private IMyInterface myBaseClassInstance;
    
            public ConsumerClass()
            {
                myBaseClassInstance = new MyBaseClass();
                //attach to the event
                myBaseClassInstance.OnSomethingHappened += MyBaseClassInstance_OnSomethingHappened;
            }
    
            private void MyBaseClassInstance_OnSomethingHappened(object sender, EventArgs e)
            {
                //react to the raised event
                throw new NotImplementedException();
            }
        }
    

    As you can see you need to implement the IMyInterface interface, and when MyBaseClass needs to raise the event you call OnSomethingHappened(sender, eventArgs);

    ConsumerClass is where you need to consume, or to do something, as a reaction to the raised event. You may consider to rename MyBaseClass to some other name, without 'Base' in it, because it is not an abstract class.