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

Event-driven design pattern in C Sharp (C#) - Mini Project: Build & Apply

Choose your learning style9 modes available
Event-driven design pattern
📖 Scenario: You are building a simple notification system where a Button can be clicked, and other parts of the program can react to this click event.This is like a real-world button that when pressed, triggers some action like turning on a light or playing a sound.
🎯 Goal: Create a basic event-driven program in C# where a Button class raises a Clicked event, and a Notifier class listens and responds by printing a message.
📋 What You'll Learn
Create a Button class with a Clicked event
Create a Notifier class with a method to handle the Clicked event
Raise the Clicked event when the button is pressed
Subscribe the Notifier to the Clicked event
Print a message when the event is handled
💡 Why This Matters
🌍 Real World
Event-driven design is used in user interfaces, games, and any program that reacts to user actions or other events.
💼 Career
Understanding events is essential for software developers working with GUI applications, web development, and real-time systems.
Progress0 / 4 steps
1
Create the Button class with a Clicked event
Create a class called Button with a public event Clicked of type EventHandler. Inside the class, add a method Press() that will later raise this event.
C Sharp (C#)
Need a hint?

Use public event EventHandler? Clicked; to declare the event.

The Press method is empty for now.

2
Create the Notifier class with an event handler method
Create a class called Notifier with a public method OnButtonClicked that takes object? sender and EventArgs e as parameters. Inside this method, write code to print "Button was clicked!".
C Sharp (C#)
Need a hint?

The event handler method must match the EventHandler delegate signature.

3
Raise the Clicked event inside the Press method and subscribe the Notifier
Inside the Press() method of Button, raise the Clicked event safely using the null-conditional operator. Then, create a Button object and a Notifier object. Subscribe the Notifier's OnButtonClicked method to the Clicked event of the Button.
C Sharp (C#)
Need a hint?

Use Clicked?.Invoke(this, EventArgs.Empty); to raise the event safely.

Subscribe with button.Clicked += notifier.OnButtonClicked;.

4
Press the button to trigger the event and print the message
In the Main method, after subscribing, call the Press() method on the button object to trigger the Clicked event and print "Button was clicked!".
C Sharp (C#)
Need a hint?

Call button.Press(); to trigger the event and see the message.