Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

EventHandler type with no event args

Tags:

c#

events

signals

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?

like image 904
Maxim V. Pavlov Avatar asked Sep 17 '11 14:09

Maxim V. Pavlov


People also ask

How do you declare an EventHandler?

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).

Can we use events without delegates?

Yes, you can declare an event without declaring a delegate by using Action. Action is in the System namespace.

What is the purpose of an EventHandler?

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.

Is an EventHandler a delegate?

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.


2 Answers

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.

like image 171
Marc Gravell Avatar answered Sep 28 '22 08:09

Marc Gravell


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);
like image 29
Eternal21 Avatar answered Sep 28 '22 06:09

Eternal21