📖 Scenario: Imagine you are building a simple alarm clock app. When the alarm time comes, you want the app to notify the user by showing a message. But you want the app to be flexible so that later you can add other actions like playing a sound or sending a message without changing the alarm clock code.
🎯 Goal: You will create a simple program that uses an event to notify when the alarm time is reached. This shows why events are useful: they let different parts of a program communicate without being tightly connected.
📋 What You'll Learn
Create a class called AlarmClock with an event called AlarmRang
Create a method called SetAlarm that triggers the AlarmRang event
Create a method called OnAlarmRang that handles the event and prints a message
Use the event to notify when the alarm time is reached
💡 Why This Matters
🌍 Real World
Events are used in apps to notify when something important happens, like a button click or a timer finishing.
💼 Career
Understanding events is key for building interactive applications and working with user interfaces or asynchronous programming.
Progress0 / 4 steps
1
Create the AlarmClock class with an event
Create a class called AlarmClock with a public event called AlarmRang of type EventHandler.
C Sharp (C#)
Hint
Use public event EventHandler AlarmRang; inside the class.
2
Add SetAlarm method to trigger the event
Add a public method called SetAlarm inside the AlarmClock class that triggers the AlarmRang event by calling it with this and EventArgs.Empty.
C Sharp (C#)
Hint
Use the null-conditional operator ?. to safely invoke the event.
3
Create OnAlarmRang method to handle the event
Create a public method called OnAlarmRang that takes object sender and EventArgs e parameters and prints "Alarm rang! Time to wake up!".
C Sharp (C#)
Hint
This method matches the event handler signature and prints the message.
4
Subscribe to the event and trigger the alarm
In the Main method, create an AlarmClock object called alarm. Subscribe the OnAlarmRang method to the AlarmRang event. Then call alarm.SetAlarm() to trigger the event and print the message.
C Sharp (C#)
Hint
Subscribe to the event using alarm.AlarmRang += alarm.OnAlarmRang; and then call alarm.SetAlarm();.
Practice
(1/5)
1. Why are events needed in C# programming?
easy
A. To allow different parts of a program to communicate without being tightly connected
B. To make the program run faster by using multiple threads
C. To store data permanently on disk
D. To create user interfaces with buttons and text boxes
Solution
Step 1: Understand the purpose of events
Events let different parts of a program talk to each other without needing to know details about each other.
Step 2: Compare with other options
Options B, C, and D describe other programming tasks but not the main reason for events.
Final Answer:
To allow different parts of a program to communicate without being tightly connected -> Option A
Quick Check:
Events enable loose communication = A [OK]
Hint: Events connect parts without tight links [OK]
Common Mistakes:
Confusing events with threading
Thinking events store data
Assuming events create UI elements
2. Which of the following is the correct way to declare an event in C#?
easy
A. public event EventHandler MyEvent;
B. public void event MyEvent();
C. event public MyEvent EventHandler;
D. public EventHandler event MyEvent;
Solution
Step 1: Recall C# event declaration syntax
Events are declared with the keyword 'event' followed by the delegate type and event name.
Step 2: Check each option
public event EventHandler MyEvent; matches the correct syntax. Options A, C, and D have incorrect order or keywords.
Final Answer:
public event EventHandler MyEvent; -> Option A
Quick Check:
Correct event syntax = B [OK]
Hint: Use 'public event DelegateType EventName;' [OK]
Common Mistakes:
Placing 'event' after the delegate type
Using 'void' with event keyword
Mixing order of keywords
3. What will be the output of this C# code?
using System;
class Program {
public static event Action OnChange;
static void Main() {
OnChange += () => Console.WriteLine("Event triggered");
OnChange?.Invoke();
}
}
medium
A. No output
B. Runtime error
C. Compilation error
D. Event triggered
Solution
Step 1: Understand event subscription and invocation
The event OnChange is subscribed with a lambda that prints "Event triggered". Then it is invoked safely with ?.Invoke().
Step 2: Predict the output
Since the event has a subscriber, invoking it prints "Event triggered" to the console.
Final Answer:
Event triggered -> Option D
Quick Check:
Subscribed event invoked prints message = D [OK]
Hint: Subscribed event prints message when invoked [OK]
Common Mistakes:
Forgetting to subscribe before invoking
Not using null-conditional operator causing errors
Expecting no output without subscription
4. Identify the error in this C# event usage:
class MyClass {
public event Action OnUpdate;
public void Update() {
OnUpdate();
}
}
medium
A. Event OnUpdate is not subscribed before invocation
B. Event OnUpdate cannot be invoked directly without null check
C. Event OnUpdate should be declared as static
D. Event OnUpdate must return a value
Solution
Step 1: Check event invocation safety
Invoking an event directly without checking if it has subscribers can cause a NullReferenceException.
Step 2: Identify the fix
Use null-conditional operator or check if OnUpdate is not null before invoking.
Final Answer:
Event OnUpdate cannot be invoked directly without null check -> Option B
Quick Check:
Always check event is not null before invoking = A [OK]
Hint: Check event is not null before calling [OK]
Common Mistakes:
Invoking event without null check
Assuming events are static by default
Expecting events to return values
5. You want to design a program where multiple parts react automatically when a data value changes. Why should you use events instead of calling methods directly?
hard
A. Events store the data changes permanently
B. Events make the program run faster by parallel processing
C. Events allow adding or removing reactions without changing the data code
D. Events prevent any part from reacting to changes
Solution
Step 1: Understand flexibility of events
Events let you add or remove listeners easily without changing the code that changes data.
Step 2: Compare with other options
Options A, B, and D describe unrelated or incorrect behaviors.
Final Answer:
Events allow adding or removing reactions without changing the data code -> Option C
Quick Check:
Events improve flexibility and decoupling = C [OK]