Search code examples
c#eventsevent-handling

How to add members to an event


I have to connect to an event like that.

for (int iii = 1; iii <= pcdApplication.Machines.Count; iii++)
{
    Machine machine = pcdApplication.Machines.Item(iii);
    machineList.Add(machine);
    machine.ErrorMsg += Machine_ErrorMsg;
}

the connected event is the following:

private void Machine_ErrorMsg(string Msg, int ErrorType)
{
    ... 
}

so here I have no indication of what is the sender machine which I would need to know its properties.

Thanks

Patrick


Solution

  • I think the only thing you could do would be to use a lambda instead of a named method, e.g.

    for (int iii = 1; iii <= pcdApplication.Machines.Count; iii++)
    {
        Machine machine = pcdApplication.Machines.Item(iii);
        machineList.Add(machine);
        machine.ErrorMsg += (Msg, ErrorType) =>
                            {
                                Console.WriteLine(machine.Name);
    
                                // ...
                            };
    }
    

    The lambda has access to variables from the current context, which a named method does not.