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

Custom event arguments in C Sharp (C#)

Choose your learning style9 modes available
Introduction

Custom event arguments let you send extra information when an event happens. This helps the event handler know more about what caused the event.

You want to tell the event handler details about the event, like a message or a number.
You need to pass multiple pieces of data when an event fires.
You want to create your own event types with specific information.
You want to make your code easier to understand by naming the data clearly.
Syntax
C Sharp (C#)
public class MyEventArgs : EventArgs
{
    public string Message { get; }

    public MyEventArgs(string message)
    {
        Message = message;
    }
}

Custom event argument classes usually inherit from EventArgs.

Make properties read-only to keep data safe after creation.

Examples
This example sends the new temperature when it changes.
C Sharp (C#)
public class TemperatureChangedEventArgs : EventArgs
{
    public double NewTemperature { get; }

    public TemperatureChangedEventArgs(double newTemp)
    {
        NewTemperature = newTemp;
    }
}
This example sends the file name and size after a download finishes.
C Sharp (C#)
public class FileDownloadedEventArgs : EventArgs
{
    public string FileName { get; }
    public int FileSize { get; }

    public FileDownloadedEventArgs(string fileName, int fileSize)
    {
        FileName = fileName;
        FileSize = fileSize;
    }
}
Sample Program

This program creates a custom event argument MessageEventArgs to send a message string when the MessageReceived event fires. The Messenger class raises the event with the message. The main program listens and prints the messages.

C Sharp (C#)
using System;

public class MessageEventArgs : EventArgs
{
    public string Message { get; }

    public MessageEventArgs(string message)
    {
        Message = message;
    }
}

public class Messenger
{
    public event EventHandler<MessageEventArgs> MessageReceived;

    public void ReceiveMessage(string message)
    {
        // Raise the event with custom arguments
        MessageReceived?.Invoke(this, new MessageEventArgs(message));
    }
}

class Program
{
    static void Main()
    {
        Messenger messenger = new Messenger();

        messenger.MessageReceived += (sender, e) =>
        {
            Console.WriteLine($"New message: {e.Message}");
        };

        messenger.ReceiveMessage("Hello, friend!");
        messenger.ReceiveMessage("How are you?");
    }
}
OutputSuccess
Important Notes

Always check if the event is not null before invoking it to avoid errors.

Custom event arguments help keep your events clear and meaningful.

Summary

Custom event arguments let you send extra data with events.

Create a class inheriting from EventArgs to hold your data.

Use these arguments when raising and handling events for clearer communication.