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
2010-04-05 10:38:20
er, but in C# 2.0
blez
2010-04-05 10:45:30
@blez: If you need a downlevel version, mention it in the question.
Richard
2010-04-05 11:16:11
+3
A:
observed[idx].WhateverEvent += delegate(sender, e)
{
// Code that was in Myhandler, can access idx
};
John Saunders
2010-04-05 11:07:07