How to add custom parameters to an event handler in C#?

In C#, you can add custom parameters in an EventHandler by creating a custom EventArgs class. Here is an example:

using System;

public class CustomEventArgs : EventArgs
{
    public string CustomParameter { get; set; }

    public CustomEventArgs(string customParameter)
    {
        CustomParameter = customParameter;
    }
}

public class MyClass
{
    public event EventHandler<CustomEventArgs> CustomEvent;

    public void OnCustomEvent(string customParameter)
    {
        CustomEvent?.Invoke(this, new CustomEventArgs(customParameter));
    }
}

public class Program
{
    public static void Main()
    {
        MyClass myClass = new MyClass();
        myClass.CustomEvent += HandleCustomEvent;

        myClass.OnCustomEvent("Hello, World!");
    }

    public static void HandleCustomEvent(object sender, CustomEventArgs e)
    {
        Console.WriteLine("Custom Event Handler invoked with parameter: " + e.CustomParameter);
    }
}

In the example above, a CustomEventArgs class was custom-defined with a CustomParameter property for storing custom parameters. Then, in the MyClass class, an EventHandler event was declared with its generic parameter specified as CustomEventArgs. When the event is triggered, a CustomEventArgs object is created using new CustomEventArgs(customParameter) and passed to the event’s triggering method, Invoke. In the event handler HandleCustomEvent, the passed custom parameter can be accessed through e.CustomParameter.

广告
Closing in 10 seconds
bannerAds