C#  

Delegates and Events in C# Windows Forms

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:

  • Passing methods as parameters

  • Callback functionality

  • Decoupling components

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!");
    }
}

Output

Hello from Delegate!

2. What is an Event?

An event is a wrapper around a delegate that enforces the publisher-subscriber pattern.

  • A publisher class defines an event.

  • A subscriber (listener) registers methods to respond when that event is triggered.

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

ConceptDescription
DelegateDefines the method signature that can be called.
EventRestricts direct delegate access — allows only += (subscribe) and -= (unsubscribe).
PublisherClass that raises (fires) the event.
SubscriberClass 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 declaration
public delegate void FileUploadHandler(int percentage);

// Publisher class
public 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
        }
    }
}

Step 2: Design the Windows Form (Form1.cs)

Add Controls:

  • ButtonbtnStart → Text = “Start Upload”

  • ProgressBarprogressBar1

  • LabellblStatus

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}%";
            }
        }
    }
}

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

ComponentPurpose
FileUploadHandlerDelegate that defines method signature
FileUploadProgressEvent 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

ScenarioDelegate/Event Use
File Upload / DownloadUpdate progress in UI
Stock Price UpdatesTrigger event when price changes
Chat ApplicationNotify when a new message arrives
Payment ProcessingRaise event when payment status changes
Logging SystemRaise event when log is written
IoT DashboardNotify 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.