Event-driven .NET: how events work

The very basis of event-driven programming is the concept of events. Events are an implementation of the Observer Pattern. With the Observer Pattern you have an observable entity and entities that want to observe that entity.

Objects with events are observable, and other objects subscribe to those events and are notified when the events happen.

The best way to understand this is by looking at the UI. In the UI we have controls, and each control has events associated with them. We can react to these events by adding event handlers that listen for the events.

Here we have a simple form with a Submit button. When I click the button, it updates a label saying that the message was sent. How does this happen?

1 – The system detects a click on the button, and executes button.OnClick()

The Button class implements a method named OnClick(). When a click is detected by the system it calls OnClick().

Events can only be invoked by the class that contains them. This is why the system must call OnClick(). The next step actually invokes the event.

2 – OnClick() invokes the Click event

The Button class inherits the Control class, which has a Click event.

public event EventHandler Click
Code language: C# (cs)

OnClick() invokes the Click event:

if(Click != null) { Click(this, e); }
Code language: C# (cs)

Note: I’ve simplified this a little bit, but you can see the actual .NET source code here.

3 – The btnSubmit_Click handler is called

In the form I subscribed to the Click event:

this.btnSubmit.Click += new System.EventHandler(this.btnSubmit_Click);
Code language: C# (cs)

When the Click event is invoked, it calls all methods that have subscribed to it. Because btnSubmit_Click is subscribed to it, it gets called.

private void btnSubmit_Click(object sender, EventArgs e) { lblStatus.Text = $"Message sent at {DateTime.Now}"; }
Code language: C# (cs)

In the end, this results in the label’s text getting updated:

Leave a Comment