tags:

views:

66

answers:

2

I have an object with event handlers and I want to make something similar to VB6 to make array of that object. Something like: MyHandler(object sender, MyEventArgs e, int IndexOfObject) <-

+3  A: 

There are some minor caveats...you have to make sure that the variable you use to pass to the handler does not change within the scope. This is due to the fact that C# supports lexical closure and uses the variables by reference (I'm sure Jon Skeet could explain it better). Just copy the variables you use or you'll get some funny behavior.

for (int i = 0; i < observed.Length; ++i)
{
    int idx = i;
    observed[idx].WhateverEvent += delegate(object sender, EventArgs e)
                                   {
                                       MyHandler(sender, e, idx);
                                   };
}
Travis Gockel
er, but in C# 2.0
blez
@blez: If you need a downlevel version, mention it in the question.
Richard
+3  A: 
observed[idx].WhateverEvent += delegate(sender, e)
                               {
                                   // Code that was in Myhandler, can access idx
                               };
John Saunders