Search code examples
c#first-class

Returning a function in C#


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

Solution

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

    (or...)

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