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