Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# Events without arguments. How do I handle them?

Tags:

c#

events

I'm currently working on a menu system for a game and I have the standard hierarchy for screens and screen elements. (Screens contain some collection of screen elements). I'd like screen elements to send an event to the screen class to declare that it's been selected. However, I don't need any event arguments in this case. I'm not sure what the syntax is to create the event without any arguments. I found a solution that passes the player index as an event argument. (My game is strictly single-player, so this is not necessary.)

public event EventHandler<PlayerIndexEventArgs> Selected;

^-- How this event is declared where PlayerIndexEventArgs inherits from EventArgs. Can I omit PlayerIndexEventArgs, or is there a default type to use here to send no arguments? (Maybe just the EventArgs base class?)

like image 881
RyanG Avatar asked Sep 05 '25 03:09

RyanG


2 Answers

You can use Action delegates. This is much more elegantly then using data you will never need (I mean EventArgs).

Here you define events:

public event Action EventWithoutParams;
public event Action<int> EventWithIntParam;

And here you fire events:

EventWithoutParams();
EventWithIntParam(123);

You can find all the information you need at Action or Action<T>.

Either of these events can be initialised with a no-op delegate ... = delegate { }; so that you don't need to check for null before firing the event.

like image 189
Dmitrii Lobanov Avatar answered Sep 09 '25 01:09

Dmitrii Lobanov


Try:

public event EventHandler Selected;

then to call..

Selected(null, EventArgs.Empty);

This way it's the default event definition and you don't need to pass any information if you don't want to.

like image 39
Quintin Robinson Avatar answered Sep 09 '25 02:09

Quintin Robinson