
Problem
Solution
Submissions
Simple Event System Using Delegates
Certification: Intermediate Level
Accuracy: 66.67%
Submissions: 3
Points: 20
Write a C# program to implement a simple event system using delegates to handle notifications between classes. You'll need to create a publisher class that can notify multiple subscribers when events occur.
Example 1
- Input: Create publisher and two subscribers, subscribe both to events, publish "System update completed"
- Output: Both subscribers receive the notification message
- Explanation:
- Step 1: Create a publisher with an event and two subscriber objects.
- Step 2: Subscribe both subscribers to the publisher's event.
- Step 3: Publisher triggers the event with message "System update completed".
- Step 4: Each subscriber's notification handler is called with the message.
- Step 5: Both subscribers print confirmation of receiving the message.
Example 2
- Input: Create publisher and two subscribers, subscribe both, publish first message, unsubscribe first subscriber, publish second message
- Output: Both subscribers receive first message, only second subscriber receives second message
- Explanation:
- Step 1: Create a publisher with an event and two subscriber objects.
- Step 2: Subscribe both subscribers to the publisher's event.
- Step 3: Publisher triggers first notification, both subscribers receive it.
- Step 4: First subscriber is unsubscribed from the event.
- Step 5: Publisher triggers second notification.
- Step 6: Only second subscriber receives the notification as the first one is no longer subscribed.
Constraints
- Your solution must use delegates and events (not interfaces)
- The system should support adding and removing subscribers dynamically
- Time Complexity: O(n) for publishing events, where n is the number of subscribers
- Space Complexity: O(n) for storing subscriber references
Editorial
My Submissions
All Solutions
| Lang | Status | Date | Code |
|---|---|---|---|
| You do not have any submissions for this problem. | |||
| User | Lang | Status | Date | Code |
|---|---|---|---|---|
| No submissions found. | ||||
Solution Hints
- Define a delegate type that matches the signature of the subscriber's notification handler method
- Use the 'event' keyword in the publisher class to declare the event based on your delegate type
- Implement methods to add (+=) and remove (-=) handlers from the event
- Check if the event has subscribers before invoking it to avoid null reference exceptions
- Consider making the subscriber identifiable (e.g., with a name property) for tracking purposes