Question

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);
Was it helpful?

Solution

northButton.Click += (s, e) => GoMethod(Direction.North);

(or...)

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

OTHER TIPS

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?

northButton.Click += (s,e) => GoMethod(Direction.North);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top