Events in C# β Simple Explanation with Examples
Introduction
Have you ever clicked a button in an app and something happened? π Thatβs because of Events in C#!
Events are a way for objects to communicate. They notify when something happens, like a button click, a file download, or a timer finishing. Events make your program more responsive and interactive!
By the end of this lesson, youβll understand how to use Events in C# with simple, fun examples! Letβs get started! π
π What You Are Going to Learn in This Lesson?
βοΈ What are Events in C#?
βοΈ Why do we need them?
βοΈ How to create and use events?
βοΈ Real-world scenario example
βοΈ Multiple coding examples
βοΈ Step-by-step explanation with output
What Are Events in C#?
An event is a special kind of delegate that is used to send notifications when something happens.
Think of a doorbell. πͺπ
- You press the doorbell β An event occurs.
- Inside the house, someone hears the bell and opens the door β A method executes.
Thatβs how Events in C# work! A class raises an event, and another class responds to it.
Syntax of Events in C#
public delegate void MyDelegate(); // Step 1: Declare a delegate
public event MyDelegate MyEvent; // Step 2: Declare an event
βοΈ A delegate acts as a function pointer.
βοΈ The event is declared using that delegate.
βοΈ Methods can subscribe or unsubscribe to the event.
Basic Example of Events in C#
Let’s create a simple event that triggers when a user logs in.
using System;
class User {
public delegate void LoginDelegate(); // Declare a delegate
public event LoginDelegate OnLogin; // Declare an event
public void Login() {
Console.WriteLine("π User logged in!");
OnLogin?.Invoke(); // Trigger the event
}
}
class Program {
static void WelcomeMessage() {
Console.WriteLine("π Welcome, user!");
}
static void Main() {
User user = new User();
user.OnLogin += WelcomeMessage; // Subscribe to event
user.Login(); // Trigger event
}
}
π Output:
π User logged in!
π Welcome, user!
π Explanation:
β LoginDelegate
is a delegate type.
β OnLogin
is an event of that type.
β Login()
method raises the event.
β WelcomeMessage()
method is executed when the event occurs.
Why Are Events Important?
β They make your program interactive.
β They improve structure β Events separate the sender and receiver.
β They allow multiple subscribers β Many methods can respond to the same event.
Real-World Example: YouTube Notifications π’
Imagine subscribing to a YouTube channel. When a new video is uploaded:
β
YouTube uploads a video (event occurs).
β
Subscribers receive a notification (event handler executes).
Let’s write this in C#! π
using System;
class YouTubeChannel {
public delegate void VideoUploadedHandler(string title);
public event VideoUploadedHandler OnVideoUploaded;
public void UploadVideo(string title) {
Console.WriteLine($"πΉ New video uploaded: {title}");
OnVideoUploaded?.Invoke(title); // Raise event
}
}
class Subscriber {
public void Notify(string title) {
Console.WriteLine($"π’ Notification: New video '{title}' is available!");
}
}
class Program {
static void Main() {
YouTubeChannel channel = new YouTubeChannel();
Subscriber user1 = new Subscriber();
channel.OnVideoUploaded += user1.Notify; // Subscribe user to event
channel.UploadVideo("C# Events Explained!"); // Upload a video
}
}
π Output:
πΉ New video uploaded: C# Events Explained!
π’ Notification: New video 'C# Events Explained!' is available!
π Explanation:
β OnVideoUploaded
event triggers when a video is uploaded.
β Notify
method subscribes to this event.
β When a video is uploaded, the event notifies the subscriber.
Another Example: Button Click Event π±οΈ
In Windows Forms or ASP.NET, events are used for button clicks.
using System;
class Button {
public delegate void ClickHandler();
public event ClickHandler OnClick;
public void Click() {
Console.WriteLine("π± Button clicked!");
OnClick?.Invoke();
}
}
class Program {
static void ShowMessage() {
Console.WriteLine("π Button was pressed!");
}
static void Main() {
Button button = new Button();
button.OnClick += ShowMessage; // Subscribe event
button.Click(); // Simulate button click
}
}
π Output:
π± Button clicked!
π Button was pressed!
Multiple Event Handlers β Calling Many Methods!
One event can call multiple methods. Letβs see how!
using System;
class Alarm {
public delegate void AlarmHandler();
public event AlarmHandler OnAlarm;
public void TriggerAlarm() {
Console.WriteLine("π¨ Alarm triggered!");
OnAlarm?.Invoke();
}
}
class Program {
static void SendSMS() {
Console.WriteLine("π± Sending SMS alert...");
}
static void CallPolice() {
Console.WriteLine("π Calling the police...");
}
static void Main() {
Alarm alarm = new Alarm();
alarm.OnAlarm += SendSMS;
alarm.OnAlarm += CallPolice;
alarm.TriggerAlarm(); // Raise event
}
}
π Output:
π¨ Alarm triggered!
π± Sending SMS alert...
π Calling the police...
π Explanation:
β SendSMS()
and CallPolice()
both execute when OnAlarm
is raised.
β This is how multiple event handlers work! π
π Next What?
Wow! π You now understand Events in C# and how they make programs more interactive!
π Next, you will learn about Built-in Delegates in C#, which make event handling even easier! Stay tuned! π
Β
Conclusion
Events in C# allow different parts of your program to communicate. They are used everywhere β in UI applications, background processes, and even notifications.
Try using events in your own projects and see how they improve your code! Happy coding! π