📖 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#)
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#)
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#)
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#)
Hint
Call doorbell.Press(); to trigger the event and see the message.
Practice
(1/5)
1. What is the main purpose of the EventHandler delegate in C#?
easy
A. To format strings for output
B. To create a new thread for event processing
C. To store data in a dictionary
D. To define a method signature for handling events
Solution
Step 1: Understand what a delegate does
A delegate defines a method signature that can be used to call methods indirectly.
Step 2: Connect delegate to event handling
The EventHandler delegate specifically defines the signature for methods that handle events.
Final Answer:
To define a method signature for handling events -> Option D
Quick Check:
EventHandler defines event method signature = D [OK]
Hint: EventHandler defines how event methods look [OK]
Common Mistakes:
Confusing EventHandler with threading
Thinking EventHandler stores data
Mixing EventHandler with string formatting
2. Which of the following is the correct syntax to declare an event using the EventHandler delegate in a class?
easy
A. public event EventHandler MyEvent;
B. public EventHandler event MyEvent;
C. event public EventHandler MyEvent();
D. public void event EventHandler MyEvent;
Solution
Step 1: Recall event declaration syntax
Events are declared with the keyword event followed by the delegate type and event name.
Step 2: Match correct syntax
public event EventHandler MyEvent; matches the correct pattern.
Final Answer:
public event EventHandler MyEvent; -> Option A
Quick Check:
Event declaration = event + delegate + name [OK]
Hint: Remember: event keyword before delegate type [OK]
Common Mistakes:
Placing 'event' after delegate type
Adding parentheses after event name
Using void instead of event keyword
3. What will be the output of the following code?
using System;
class Program {
public static event EventHandler OnAction;
static void Main() {
OnAction += (sender, e) => Console.WriteLine("Action happened!");
OnAction?.Invoke(null, EventArgs.Empty);
}
}
medium
A. Action happened!
B. No output
C. NullReferenceException
D. Compilation error
Solution
Step 1: Understand event subscription
The lambda expression subscribes a method that prints "Action happened!" to the event OnAction.
Step 2: Invoke the event safely
The event is invoked with ?.Invoke, so it calls the subscribed method, printing the message.
Final Answer:
Action happened! -> Option A
Quick Check:
Subscribed event invoked prints message = A [OK]
Hint: ?.Invoke calls event only if not null [OK]
Common Mistakes:
Forgetting to subscribe to the event
Not using null-conditional operator causing errors
Expecting no output without invocation
4. Identify the error in this event usage code:
public class Button {
public event EventHandler Click;
public void SimulateClick() {
Click(null, EventArgs.Empty);
}
}
medium
A. EventHandler delegate cannot use EventArgs.Empty
B. Event must be invoked with a sender object, not null
C. Event should be checked for null before invoking
D. SimulateClick method must be static
Solution
Step 1: Check event invocation safety
Events can be null if no subscribers exist, so invoking without null check causes runtime error.
Step 2: Correct usage
Use Click?.Invoke(this, EventArgs.Empty); to safely invoke the event.
Final Answer:
Event should be checked for null before invoking -> Option C
Quick Check:
Always check event for null before invoke [OK]
Hint: Use ?.Invoke to avoid null errors [OK]
Common Mistakes:
Invoking event directly without null check
Assuming sender cannot be null
Making event handler static unnecessarily
5. You want to create a custom event that sends a string message to subscribers. Which is the best way to define the event and its arguments using the EventHandler pattern?
hard
A. Declare event as EventHandler and send string directly as sender parameter
B. Create a class inheriting from EventArgs with a string property, then declare event as EventHandler<YourArgs>
C. Use Action<string> delegate instead of EventHandler for the event
D. Declare event as EventHandler and ignore sending any data
Solution
Step 1: Understand custom event data
To send extra info, create a class derived from EventArgs with needed properties.
Step 2: Use generic EventHandler with custom args
Declare event as EventHandler<YourArgs> to pass the custom data safely.
Final Answer:
Create a class inheriting from EventArgs with a string property, then declare event as EventHandler<YourArgs> -> Option B
Quick Check:
Custom EventArgs + EventHandler<T> = B [OK]
Hint: Use EventHandler<T> with custom EventArgs for extra data [OK]
Common Mistakes:
Passing data via sender parameter
Using Action delegate instead of EventHandler
Ignoring event data when needed
Recommended
Ready to prove it?
Pass the test and this pattern moves unknownstrongwhile earning +1 Grip toward your certificate.