Event-Driven C#: How to Make Your Code Listen and React

Click follow to turn your code into an attentive listener.

Alex Maher

--

Hey everyone!

If you’re like me, I learn things best when they’re simple to understand and fun at the same time!

When I first learned about delegates, I found it hard to grasp the concept.

So I’ll do my best to make this easy for beginners to understand.

Alright, let’s get going!

Imagine you’re making a program, and you want something to happen when you click a button.

You’re setting up an event (the button click) and telling your program, “Hey, when someone clicks this button, do this thing for me, okay?” That’s event-driven programming in a nutshell.

Here’s how it goes down in C#.

Defining a Delegate

Think of this as creating a custom invitation for a party. It tells your guests (the event handlers) what kind of party it is and what they need to bring.

public delegate void FileDownloadedEventHandler(object source, FileEventArgs args);

Declare an Event

Next, you declare an event in a class using the delegate type. The class that publishes the event is known as the publisher.

public event FileDownloadedEventHandler FileDownloaded;

Raising the Event

The publisher class provides a protected virtual method to raise the event. This method is conventionally named with the “On” prefix followed by the event name.

protected virtual void OnFileDownloaded(FileEventArgs e)
{
FileDownloaded?.Invoke(this, e);
}

Write Event Handlers

Subscribers write event handlers that match the delegate signature to respond to the event.

void OnFileDownloaded(object source, FileEventArgs e)
{
Console.WriteLine($"File downloaded: {e.FileName}");
}

Subscribe to the Event

Finally, subscribers register their event handlers with the event.

--

--

Alex Maher

.NET C# dev with 10+ yrs exp, self-taught & passionate web developer. Sharing tips & experiences in C# and web dev.