tags:

views:

153

answers:

5

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

A: 

(Maybe just the EventArgs base class?)

You should do exactly that.

From the MSDN Docs on EventArgs:

This class contains no event data; it is used by events that do not pass state information to an event handler when an event is raised.

Ryan
+5  A: 

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.

Quintin Robinson
This guy should really be using the Action variables as they're less of a hassle and work just fine in most cases.
RCIX
+1  A: 

You can just write:

public event EventHandler Selected;
Groky
A: 

Going by the PlayerIndexEventArgs type you mentioned, I am assuming you are using XNA, right? If so, take a look at the Game State Management sample. If not the code might help you understand how to do it anyway.

Joe
+6  A: 

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

Dmitry Lobanov
Smart idea, have no clue why people want to do all of the unnecessary work of events only to waste their advantages!
RCIX
Unfortunately, no, simply calling `EventWithoutParams()` is not the best way to fire the event. The reason, as Eric Lippert points out, is that you can end up with a NullReferenceException. What you need to do is copy the delegate reference: `Action eventWithoutParamsTemp = EventWithoutParams;` and then perform a null check: `if (eventWithoutParamsTemp != null) eventWithoutParamsTemp();` Reference: http://blogs.msdn.com/ericlippert/archive/2009/04/29/events-and-races.aspx
jasonh
Thanks, jasonh, for your comment. I omited this in order to concentrate on using Action delegate itself, not on correct using of events. I thought that everybody already knows about how to use events :) If not - they should read Jefry Richter's book.
Dmitry Lobanov