Search code examples
c#events.net-2.0event-handling

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


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.


Solution

  • 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.....
        }
    }