blez
blez

Reputation: 5037

How to simulate array of events in C#? (like in VB6)

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)

Upvotes: 1

Views: 180

Answers (2)

John Saunders
John Saunders

Reputation: 161783

observed[idx].WhateverEvent += delegate(sender, e)
{
    // Code that was in Myhandler, can access idx
};

Upvotes: 3

Travis Gockel
Travis Gockel

Reputation: 27633

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

Upvotes: 3

Related Questions