Passing arguments to an event handler

user476566 picture user476566 · Sep 6, 2012 · Viewed 51.9k times · Source

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

Answer

ColinE picture ColinE · Sep 6, 2012

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

}