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

Why events are needed in C Sharp (C#) - See It in Action

Choose your learning style9 modes available
Why events are needed
📖 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#)
Need a 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#)
Need a 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#)
Need a 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#)
Need a hint?

Subscribe to the event using alarm.AlarmRang += alarm.OnAlarmRang; and then call alarm.SetAlarm();.