0
0
CsharpConceptBeginner · 3 min read

What is Event in C#: Explanation and Example

In C#, an event is a way for a class to provide notifications to other classes when something happens. It acts like a message system where one class can signal that an action occurred, and other classes can respond by subscribing to that event.
⚙️

How It Works

Think of an event in C# like a doorbell in a house. When someone presses the doorbell (the event), the people inside (subscribers) hear it and can react, like opening the door. The class that owns the event is like the doorbell, and other classes can choose to listen and respond.

Technically, an event is built on top of a delegate, which is a type that holds references to methods. When the event is triggered (or "raised"), it calls all the methods that have subscribed to it. This allows different parts of a program to communicate without tightly linking their code.

💻

Example

This example shows a simple event where a Clock class raises an event every second, and a Display class listens and prints the time.

csharp
using System;
using System.Threading;

class Clock
{
    public event Action? Tick;

    public void Start()
    {
        while (true)
        {
            Thread.Sleep(1000);
            Tick?.Invoke();
        }
    }
}

class Display
{
    public void Subscribe(Clock clock)
    {
        clock.Tick += ShowTime;
    }

    private void ShowTime()
    {
        Console.WriteLine($"Tick: {DateTime.Now:T}");
    }
}

class Program
{
    static void Main()
    {
        Clock clock = new Clock();
        Display display = new Display();
        display.Subscribe(clock);
        clock.Start();
    }
}
Output
Tick: 14:30:01 Tick: 14:30:02 Tick: 14:30:03 ... (prints every second)
🎯

When to Use

Use events in C# when you want to notify other parts of your program that something important happened without making those parts tightly connected. This is common in user interfaces, where clicking a button raises an event that other code listens to.

Events are also useful in games, timers, or any system where actions happen asynchronously and multiple components need to react independently.

Key Points

  • Events allow communication between classes without tight coupling.
  • They are based on delegates, which hold references to methods.
  • Subscribers register methods to be called when the event is raised.
  • Events are commonly used in UI programming and asynchronous operations.

Key Takeaways

An event in C# lets a class notify others when something happens.
Events use delegates to call subscribed methods automatically.
Use events to keep code loosely connected and responsive.
Common uses include UI actions, timers, and asynchronous events.