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

Raising events safely in C Sharp (C#) - Mini Project: Build & Apply

Choose your learning style9 modes available
Raising events safely
📖 Scenario: Imagine you are building a simple notification system where a class sends messages to subscribers when something important happens.
🎯 Goal: You will create a class with an event, set up a subscriber method, and raise the event safely to notify subscribers without errors.
📋 What You'll Learn
Create a delegate type called NotifyEventHandler that takes object sender and EventArgs e parameters
Create a class called Notifier with an event called OnNotify of type NotifyEventHandler
Write a method RaiseNotification in Notifier that raises OnNotify safely using a local copy
Create a subscriber method called HandleNotification that prints a message when notified
Subscribe HandleNotification to the OnNotify event
Call RaiseNotification to trigger the event and display the message
💡 Why This Matters
🌍 Real World
Events are used in user interfaces, messaging systems, and many applications to notify parts of a program when something happens.
💼 Career
Understanding how to raise events safely is important for writing reliable and thread-safe C# applications, a common requirement in software development jobs.
Progress0 / 4 steps
1
Create the delegate and Notifier class with event
Create a delegate called NotifyEventHandler that takes object sender and EventArgs e. Then create a class called Notifier with an event OnNotify of type NotifyEventHandler.
C Sharp (C#)
Need a hint?

Delegates define the shape of methods that can be called. Events use delegates to notify subscribers.

2
Add the RaiseNotification method with safe event raising
Inside the Notifier class, add a method called RaiseNotification that creates a local copy of OnNotify and invokes it with this and EventArgs.Empty if the copy is not null.
C Sharp (C#)
Need a hint?

Copy the event delegate to a local variable to avoid race conditions when raising events.

3
Create a subscriber method and subscribe to the event
Outside the Notifier class, create a method called HandleNotification that takes object sender and EventArgs e and prints "Notification received!". Then create a Notifier object called notifier and subscribe HandleNotification to notifier.OnNotify.
C Sharp (C#)
Need a hint?

Subscriber methods must match the delegate signature. Use += to subscribe to events.

4
Call RaiseNotification to trigger the event and print the message
In the Main method, after subscribing HandleNotification to notifier.OnNotify, call notifier.RaiseNotification() to raise the event and display the message.
C Sharp (C#)
Need a hint?

Calling the method that raises the event will notify all subscribers and print the message.