0
0
C Sharp (C#)programming~30 mins

EventHandler delegate pattern in C Sharp (C#) - Mini Project: Build & Apply

Choose your learning style9 modes available
EventHandler Delegate Pattern
📖 Scenario: Imagine you are building a simple notification system for a doorbell. When someone presses the doorbell, the system should notify the user by printing a message.
🎯 Goal: You will create a program that uses the EventHandler delegate pattern to notify when the doorbell is pressed.
📋 What You'll Learn
Create a class called Doorbell with an event using EventHandler
Create a method called Press in Doorbell that triggers the event
Create a subscriber method called OnDoorbellPressed that handles the event
Subscribe the OnDoorbellPressed method to the doorbell event
Trigger the event by calling Press and print the notification message
💡 Why This Matters
🌍 Real World
EventHandler delegate pattern is used in many applications to notify when something happens, like button clicks, sensor alerts, or data changes.
💼 Career
Understanding events and delegates is essential for C# developers working on desktop apps, web apps, or any interactive software.
Progress0 / 4 steps
1
Create the Doorbell class with an event
Create a class called Doorbell with a public event called Pressed of type EventHandler.
C Sharp (C#)
Need a hint?

Use public event EventHandler Pressed; inside the Doorbell class.

2
Add the Press method to trigger the event
Inside the Doorbell class, add a public method called Press that triggers the Pressed event safely using Pressed?.Invoke(this, EventArgs.Empty);.
C Sharp (C#)
Need a hint?

Use the null-conditional operator ?. to safely invoke the event.

3
Create the subscriber method and subscribe to the event
Outside the Doorbell class, create a static method called OnDoorbellPressed that matches the EventHandler signature and prints "Doorbell was pressed!". Then, create a Main method where you create a Doorbell object, subscribe OnDoorbellPressed to the Pressed event.
C Sharp (C#)
Need a hint?

The subscriber method must match EventHandler signature: void MethodName(object sender, EventArgs e).

4
Trigger the event and print the notification
In the Main method, after subscribing, call the Press method on the doorbell object to trigger the event and print the message.
C Sharp (C#)
Need a hint?

Call doorbell.Press(); to trigger the event and see the message.