tags:

views:

158

answers:

3

I have this snippet

private void westButton_click(object sender, EventArgs ea)
{
    PlayerCharacter.Go(Direction.West);
}

repeated for North, South and East.

How can I declare a function that'd let me generate methods like ir programmatically?

e.g., I'd like to be able to call

northButton.Click += GoMethod(Direction.North);

instead of defining the method, and then

northButton.Click += new EventHandler(northButton.Click);
A: 
northButton.Click += (s,e) => GoMethod(Direction.North);
Jim
() => PlayerCharacter.Go(Direction.North)
Joel Coehoorn
How are you adding a lambda expression that takes no parameters to an event as a handler that expects a delegate that takes two parameters: object and EventArgs? It should be (s,e) => PlayerCharacter.Go(Direction.North) or delegate { PlayerCharacter.Go(Direction.North);}
Mehmet Aras
Thanks. Fixed.
Jim
A: 

I seem to have found a solution:

private EventHandler GoMethod(Direction dir)
{
    return new EventHandler((object sender, EventArgs ea) => PlayerCharacter.Go(dir));
}

My only concern would be about binding time; if PlayerCharacter is null when I call GoMethod, what would happen?

Tordek
The PlayerCharacter and dir variables are captured (closed over) with a closure. The compiler will generate extra code behind the scenes to "hoist" them into a their own private class and instance so they retain their state at the time this code ran.
Joel Coehoorn
+4  A: 
northButton.Click += (s, e) => GoMethod(Direction.North);

(or...)

northButton.Click += (s, e) => PlayerCharacter.Go(Direction.North);
Ron Klein