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

Publisher-subscriber execution model in C Sharp (C#) - Mini Project: Build & Apply

Choose your learning style9 modes available
Publisher-Subscriber Execution Model in C#
📖 Scenario: Imagine you are building a simple notification system where different parts of a program can listen for messages and react when something important happens.
🎯 Goal: You will create a basic publisher-subscriber model in C#. The publisher will send messages, and subscribers will receive and display those messages.
📋 What You'll Learn
Create a delegate type for the event
Create a publisher class with an event
Create subscriber classes with methods to handle the event
Subscribe the subscriber methods to the publisher's event
Trigger the event to notify all subscribers
Print the messages received by subscribers
💡 Why This Matters
🌍 Real World
Publisher-subscriber models are used in chat apps, notification systems, and event-driven programming to let parts of a program talk to each other easily.
💼 Career
Understanding events and delegates in C# is essential for building responsive applications and working with frameworks like .NET that use event-driven designs.
Progress0 / 4 steps
1
Create a delegate and a publisher class with an event
Create a delegate called MessageHandler that takes a string parameter. Then create a class called Publisher with an event called MessageSent of type MessageHandler.
C Sharp (C#)
Need a hint?

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

2
Add a method in Publisher to send messages
In the Publisher class, add a method called SendMessage that takes a string parameter called message. Inside this method, invoke the MessageSent event with the message if it is not null.
C Sharp (C#)
Need a hint?

Check if the event has subscribers before calling it to avoid errors.

3
Create subscriber classes with methods to handle messages
Create two classes called SubscriberA and SubscriberB. Each class should have a method called OnMessageReceived that takes a string parameter called message and prints "Subscriber A received: {message}" or "Subscriber B received: {message}" respectively.
C Sharp (C#)
Need a hint?

Use System.Console.WriteLine with string interpolation to print messages.

4
Subscribe methods and send a message
In the Main method, create instances of Publisher, SubscriberA, and SubscriberB. Subscribe SubscriberA.OnMessageReceived and SubscriberB.OnMessageReceived to the Publisher.MessageSent event. Then call SendMessage on the publisher with the message "Hello Subscribers!". Print the output.
C Sharp (C#)
Need a hint?

Use the += operator to subscribe methods to events.