In C#, you can define an event handler with a delegate that accepts parameters using the following steps:
- Define a delegate that matches the signature of the event handler. The delegate specifies the parameters and return type of the event handler method. For example, let’s create a delegate named
EventHandlerWithParameterthat takes an integer parameter and doesn’t return anything:
delegate void EventHandlerWithParameter(int parameter);
Declare an event of the delegate type in the class where you want to define the event handler. For instance, let’s say we have a class named
EventPublisher that declares an event named
public event EventHandlerWithParameter SomeEvent;
// Rest of the class code...
Create a method that matches the delegate’s signature. This method will serve as the event handler and will be called when the event is triggered. For example, let’s create a method named
HandleEvent that takes an integer parameter:
void HandleEvent(int parameter)
// Event handling logic...
Subscribe to the event by adding the event handler method to the event delegate’s invocation list. In this case, you can use the
+= operator to add the
HandleEvent method to the
EventPublisher publisher = new EventPublisher();
publisher.SomeEvent += HandleEvent;
Trigger the event when desired. In your code, call the event by using the event publisher object and provide the necessary parameter(s):
int parameterValue = 42;
The event handler method (
HandleEvent) will be executed, and it will receive the parameter value passed when invoking the event.
That’s how you can define an event handler with a delegate that accepts parameters in C#.