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

Why events are needed in C Sharp (C#)

Choose your learning style9 modes available
Introduction

Events help programs respond to actions or changes automatically. They let parts of a program talk to each other without being tightly connected.

When a button is clicked in a user interface and you want to run some code.
When a file finishes downloading and you want to start processing it.
When a sensor detects a change and you want to update the display.
When a timer reaches zero and you want to trigger an alert.
Syntax
C Sharp (C#)
public event EventHandler EventName;

// To raise the event:
EventName?.Invoke(this, EventArgs.Empty);

Events are declared with the event keyword.

They use delegates to define the method signature for event handlers.

Examples
This example shows a simple event named Clicked that can be triggered.
C Sharp (C#)
public event EventHandler Clicked;

// Raise the event
Clicked?.Invoke(this, EventArgs.Empty);
Here, a custom delegate is used to define the event's method signature.
C Sharp (C#)
public delegate void ThresholdReachedEventHandler(object sender, EventArgs e);
public event ThresholdReachedEventHandler ThresholdReached;
Sample Program

This program creates a button that raises an event when pressed. The main program listens to the event and responds by printing a message.

C Sharp (C#)
using System;

class Button
{
    public event EventHandler Clicked;

    public void Press()
    {
        Console.WriteLine("Button was pressed.");
        Clicked?.Invoke(this, EventArgs.Empty);
    }
}

class Program
{
    static void Main()
    {
        Button button = new Button();
        button.Clicked += Button_Clicked;
        button.Press();
    }

    private static void Button_Clicked(object sender, EventArgs e)
    {
        Console.WriteLine("Event handler: Button was clicked!");
    }
}
OutputSuccess
Important Notes

Events help keep code organized by separating the action from the response.

Using events makes programs easier to maintain and extend.

Summary

Events allow parts of a program to communicate without tight connections.

They are useful for responding to user actions or changes automatically.

Events improve code organization and flexibility.