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

Event declaration syntax in C Sharp (C#)

Choose your learning style9 modes available
Introduction

Events let parts of your program talk to each other when something happens. Declaring an event sets up a way to send these messages.

You want to notify other parts of your program when a button is clicked.
You need to alert multiple listeners when data changes.
You want to create a custom signal that other code can respond to.
You are building a user interface that reacts to user actions.
You want to separate the code that triggers an action from the code that responds.
Syntax
C Sharp (C#)
access_modifier event EventHandler EventName;

// Or with custom delegate:
access_modifier event DelegateType EventName;

access_modifier is usually public, private, or protected.

EventHandler is a common delegate type for events that don't send extra data.

Examples
Declares a public event named Clicked using the built-in EventHandler delegate.
C Sharp (C#)
public event EventHandler Clicked;
Declares a private event named DataChanged that sends custom data with MyEventArgs.
C Sharp (C#)
private event EventHandler<MyEventArgs> DataChanged;
Declares a custom delegate ThresholdReachedHandler and an event ThresholdReached using it.
C Sharp (C#)
public delegate void ThresholdReachedHandler(int threshold);
public event ThresholdReachedHandler ThresholdReached;
Sample Program

This program declares an event named SomethingHappened. It subscribes a simple message to it and then triggers the event, causing the message to print.

C Sharp (C#)
using System;

class Program
{
    // Declare an event using EventHandler delegate
    public event EventHandler SomethingHappened;

    public void TriggerEvent()
    {
        // Check if there are subscribers
        SomethingHappened?.Invoke(this, EventArgs.Empty);
    }

    static void Main()
    {
        Program p = new Program();

        // Subscribe to the event
        p.SomethingHappened += (sender, e) =>
        {
            Console.WriteLine("Event was triggered!");
        };

        // Trigger the event
        p.TriggerEvent();
    }
}
OutputSuccess
Important Notes

Always check if the event has subscribers before triggering it to avoid errors.

Events use delegates behind the scenes to hold references to subscriber methods.

Use ?.Invoke syntax to safely call events in modern C#.

Summary

Events let objects send messages to others when something happens.

Declare events with the event keyword and a delegate type.

Use ?.Invoke to trigger events safely.