Complete C# Tutorial

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 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! πŸŽ‰

Leave a Comment

Share this Doc

Events in C#

Or copy link