Introduction
In C#, Delegates and Events are core building blocks of event-driven programming — meaning actions happen in response to user interactions or specific triggers.
You use them daily when working with:
Button clicks (button.Click += …)
Background worker notifications
Real-time status updates
Logging or notification systems
Let’s understand how they work and then build a Windows Forms real-time application.
1. What is a Delegate?
A delegate is a type that holds a reference to a method.
You can think of it as a pointer to a function (type-safe).
Delegates allow:
Basic Example
public delegate void MyDelegate(string message);
class Program{
static void ShowMessage(string msg)
{
Console.WriteLine(msg);
}
static void Main()
{
MyDelegate del = ShowMessage;
del("Hello from Delegate!");
}}
C#
Output
Hello from Delegate!
2. What is an Event?
An event is a wrapper around a delegate that enforces the publisher-subscriber pattern.
Example in daily life:
Think of a YouTube channel as a publisher, and its subscribers get notifications when a new video (event) is published.
3. Relationship Between Delegate and Event
| Concept | Description |
|---|
| Delegate | Defines the method signature that can be called. |
| Event | Restricts direct delegate access — allows only += (subscribe) and -= (unsubscribe). |
| Publisher | Class that raises (fires) the event. |
| Subscriber | Class or method that handles the event. |
4. Real-Time Example in Windows Forms
Let’s create a Windows Forms Application demonstrating how delegates and events can update the UI dynamically — simulating a file upload progress tracker.
Step 1: Create Delegate and Event
// Delegate declarationpublic delegate void FileUploadHandler(int percentage);
// Publisher classpublic class FileUploader{
public event FileUploadHandler FileUploadProgress;
public void StartUpload()
{
for (int i = 0; i <= 100; i += 10)
{
System.Threading.Thread.Sleep(200); // Simulate time delay
OnFileUploadProgress(i);
}
}
protected virtual void OnFileUploadProgress(int percentage)
{
if (FileUploadProgress != null)
{
FileUploadProgress(percentage); // Raise event
}
}}
C#
Step 2: Design the Windows Form (Form1.cs)
Add Controls:
Step 3: Form Code Behind
using System;using System.Threading.Tasks;using System.Windows.Forms;
namespace WinFormsDemo{
public partial class Form1 : Form
{
private FileUploader uploader;
public Form1()
{
InitializeComponent();
}
private async void btnStart_Click(object sender, EventArgs e)
{
uploader = new FileUploader();
// Subscribe to the event
uploader.FileUploadProgress += UpdateProgress;
lblStatus.Text = "Uploading...";
progressBar1.Value = 0;
// Run file upload on a background thread
await Task.Run(() => uploader.StartUpload());
lblStatus.Text = "Upload Complete!";
}
private void UpdateProgress(int percentage)
{
// Safely update UI from event (background thread)
if (progressBar1.InvokeRequired)
{
progressBar1.Invoke(new Action(() => progressBar1.Value = percentage));
lblStatus.Invoke(new Action(() => lblStatus.Text = $"Uploading... {percentage}%"));
}
else
{
progressBar1.Value = percentage;
lblStatus.Text = $"Uploading... {percentage}%";
}
}
}}
C#
Output Example
When the user clicks “Start Upload”:
The delegate points to UpdateProgress()
The event fires every 10% progress
The label and progress bar update live
At 100%, the message changes to “Upload Complete!”
5. Explanation
| Component | Purpose |
|---|
| FileUploadHandler | Delegate that defines method signature |
| FileUploadProgress | Event that subscribers can listen to |
| StartUpload() | Publisher method that raises the event |
| UpdateProgress() | Subscriber method that handles the event |
| Invoke() | Ensures UI thread updates safely |
6. Real-Time Use Cases
| Scenario | Delegate/Event Use |
|---|
| File Upload / Download | Update progress in UI |
| Stock Price Updates | Trigger event when price changes |
| Chat Application | Notify when a new message arrives |
| Payment Processing | Raise event when payment status changes |
| Logging System | Raise event when log is written |
| IoT Dashboard | Notify when sensor data updates |
Key Takeaways
Delegates – Function pointers (methods as variables)
Events – Triggered actions using delegates (publisher/subscriber model)
Real-world apps – Use events for UI updates, notifications, and background operations
Windows Forms – Events are used behind every control like Button.Click or TextChanged
Conclusion
Delegates and Events are the backbone of event-driven programming in C#.
They help create loose coupling, reusable components, and responsive user interfaces.
By understanding how delegates and events work together, you can design better asynchronous, interactive, and maintainable Windows Forms or ASP.NET applications.