Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to subscribe to other class' events in C#?

Tags:

A simple scenario: a custom class that raises an event. I wish to consume this event inside a form and react to it.

How do I do that?

Note that the form and custom class are separate classes.

like image 934
sarsnake Avatar asked May 27 '09 00:05

sarsnake


People also ask

Can an event have multiple subscribers?

An event can have multiple subscribers. A subscriber can handle multiple events from multiple publishers. Events that have no subscribers are never raised.

How do you subscribe to a method in C#?

To subscribe to events by using the Visual Studio IDEOn top of the Properties window, click the Events icon. Double-click the event that you want to create, for example the Load event. Visual C# creates an empty event handler method and adds it to your code. Alternatively you can add the code manually in Code view.

Which operator would you use to have an event handler method subscribe to an event?

+= subscribes to an event. The delegate or method on the right-hand side of the += will be added to an internal list that the event keeps track of, and when the owning class fires that event, all the delegates in the list will be called.

How you can add an event handler?

Right-click the control for which you want to handle the notification event. On the shortcut menu, choose Add Event Handler to display the Event Handler Wizard. Select the event in the Message type box to add to the class selected in the Class list box.


2 Answers

public class EventThrower
{
    public delegate void EventHandler(object sender, EventArgs args) ;
    public event EventHandler ThrowEvent = delegate{};

    public void SomethingHappened() => ThrowEvent(this, new EventArgs());
}

public class EventSubscriber
{
    private EventThrower _Thrower;

    public EventSubscriber()
    {
        _Thrower = new EventThrower();
        // using lambda expression..could use method like other answers on here

        _Thrower.ThrowEvent += (sender, args) => { DoSomething(); };
    }

    private void DoSomething()
    {
       // Handle event.....
    }
}
like image 176
CSharpAtl Avatar answered Sep 24 '22 20:09

CSharpAtl


Inside your form:

private void SubscribeToEvent(OtherClass theInstance) => theInstance.SomeEvent += this.MyEventHandler;

private void MyEventHandler(object sender, EventArgs args)
{
    // Do something on the event
}

You just subscribe to the event on the other class the same way you would to an event in your form. The three important things to remember:

  1. You need to make sure your method (event handler) has the appropriate declaration to match up with the delegate type of the event on the other class.

  2. The event on the other class needs to be visible to you (ie: public or internal).

  3. Subscribe on a valid instance of the class, not the class itself.

like image 31
Reed Copsey Avatar answered Sep 21 '22 20:09

Reed Copsey