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

Event declaration syntax in C Sharp (C#) - Mini Project: Build & Apply

Choose your learning style9 modes available
Event Declaration Syntax in C#
📖 Scenario: You are building a simple notification system where a class can notify others when an event happens.
🎯 Goal: Create a class with an event declaration and trigger the event to notify subscribers.
📋 What You'll Learn
Declare an event using the event keyword
Use a delegate type EventHandler for the event
Create a method to raise the event
Subscribe to the event and handle it by printing a message
💡 Why This Matters
🌍 Real World
Events are used in user interfaces, game programming, and many applications to notify parts of a program when something happens.
💼 Career
Understanding event declaration and handling is essential for C# developers working on desktop apps, web apps, and game development.
Progress0 / 4 steps
1
Create a class with an event declaration
Create a class called Notifier and declare an event called OnNotify using the delegate type EventHandler.
C Sharp (C#)
Need a hint?

Use public event EventHandler OnNotify; inside the class.

2
Add a method to raise the event
Inside the Notifier class, add a public method called Notify that raises the OnNotify event if it has subscribers.
C Sharp (C#)
Need a hint?

Use the null-conditional operator ?. to safely invoke the event.

3
Subscribe to the event and handle it
Create a Main method. Inside it, create an instance of Notifier called notifier. Subscribe to the OnNotify event with a lambda that prints "Event triggered!".
C Sharp (C#)
Need a hint?

Use notifier.OnNotify += (sender, e) => Console.WriteLine("Event triggered!"); to subscribe.

4
Trigger the event and display the output
In the Main method, after subscribing, call the Notify method on notifier to trigger the event and print the message.
C Sharp (C#)
Need a hint?

Call notifier.Notify(); to raise the event and see the message.