28

In the below code, I am defining an event handler and would like to access the age and name variable from that without declaring the name and age globally. Is there a way I can say e.age and e.name?

void Test(string name, string age)
{
    Process myProcess = new Process(); 
    myProcess.Exited += new EventHandler(myProcess_Exited);
}

private void myProcess_Exited(object sender, System.EventArgs e)
{
  //  I want to access username and age here. ////////////////
    eventHandled = true;
    Console.WriteLine("Process exited");
}
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
user476566
  • 1,319
  • 3
  • 26
  • 42
  • Same as http://stackoverflow.com/questions/8644253/c-sharp-pass-parameter-to-eventhandler – codingbiz Sep 06 '12 at 05:30
  • possible duplicate of [C# passing extra parameters to an event handler?](http://stackoverflow.com/questions/4215845/c-sharp-passing-extra-parameters-to-an-event-handler) – nawfal May 06 '13 at 05:28

2 Answers2

64

Yes, you could define the event handler as a lambda expression:

void Test(string name, string age)
{
  Process myProcess = new Process(); 
  myProcess.Exited += (sender, eventArgs) =>
    {
      // name and age are accessible here!!
      eventHandled = true;
      Console.WriteLine("Process exited");
    }

}
ColinE
  • 68,894
  • 15
  • 164
  • 232
  • 3
    Perfect solution. This is clean and powerfull. Thanks – Diego Mendes Jul 03 '13 at 03:19
  • 1
    Really, very elegant solution! – Pratik Singhal Dec 27 '13 at 12:23
  • What happens if you call Test(...) again before myProcess has exited? Does the lambda create a hidden class that hold the arguments from the Test(...) function? – MJLaukala May 02 '14 at 13:30
  • 5
    This lambda method makes reuse impossible. If you have several senders that should act the same, a function after the += is much clearer and maintainable then using the lambda expression. Suppose you 10 buttons, which should all do the same when pressed, with only one small exception, depending on the sender, then using the lambda expression requires you to write the lambda expression after the += for every button clicked event. Are you sure they will remain the same after code changes? – Harald Coppoolse Jul 24 '14 at 07:30
11

If you want to access username and age, you should create handler which uses custom EventArgs (inherited from EventArgs class), like following:


public class ProcessEventArgs : EventArgs
{
  public string Name { get; internal set; }
  public int  Age { get; internal set; }
  public ProcessEventArgs(string Name, int Age)
  {
    this.Name = Name;
    this.Age = Age;
  }
}

and the delegate

public delegate void ProcessHandler (object sender,  ProcessEventArgs data);
Maciek Talaska
  • 1,628
  • 1
  • 14
  • 22