When we want to pass data to an event subscriber, we use EventArgs (or CustomEventArgs) for this.
.Net provides a build in type EventHandler that uses as a parameter an instance of EventArgs class that is build in as well.
What about cases, when I need to notify a subscriber that some action is over, for example search is over? I don't want to even use EventArgs, that won't contain anything.
Is there a build in type for signaling another class, without the need to use empty EventArgs?
Use the EventHandler delegate for all events that do not include event data. Use the EventHandler<TEventArgs> delegate for events that include data about the event. These delegates have no return type value and take two parameters (an object for the source of the event, and an object for event data).
Yes, you can declare an event without declaring a delegate by using Action. Action is in the System namespace.
In programming, an event handler is a callback routine that operates asynchronously once an event takes place. It dictates the action that follows the event. The programmer writes a code for this action to take place. An event is an action that takes place when a user interacts with a program.
The EventHandler delegate is a predefined delegate that specifically represents an event handler method for an event that does not generate data. If your event does generate data, you must use the generic EventHandler<TEventArgs> delegate class.
I really would advise you to use the standard EventHandler pattern here and just pass EventArgs.Empty
. However, you can use Action
as an event type if you really want – it is just unusual.
Use Actions (below answer copied from https://stackoverflow.com/a/1689341/1288473):
Declaring:
public event Action EventWithoutParams;
public event Action<int> EventWithIntParam;
Calling:
EventWithoutParams?.Invoke();
EventWithIntParam?.Invoke(123);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With