Dave Bish
Dave Bish

Reputation: 19646

Can someone explain what is happening behind the scenes?

It's not entirely obvious to me what's happening in this situation.

I'd expect both functions to be fired.

Either the EventHander class is storing the list of functions to fire as an array - and the array is copied to a new one every time something is added/removed - or when the assignment is made, the whole thing is copied to a new "collection" - and not just a reference.

Somebody please enlighten me :D

Here's a little Linqpad script:

public class Moop
{
    public EventHandler myEvent;
}

void Main()
{
    var moo = new Moop();
    moo.myEvent += (o, sender) => { "Added to Moop #1".Dump(); };   

    var moo2 = new Moop();

    //Copy the reference, I assume?
    moo2.myEvent = moo.myEvent;

    moo2.myEvent += (o, sender) => { "Added to Moop #2".Dump(); }; 

    //Fire the event on #1
    moo.myEvent(null, null);
}

Upvotes: 8

Views: 176

Answers (1)

Roy Dictus
Roy Dictus

Reputation: 33139

Event handler lists are delegates, and delegates are immutable -- like strings. So you do copy the delegate, and the second event handler gets "added to" the 2nd delegate, not the first.

You can find out more about delegates at http://www.c-sharpcorner.com/uploadfile/Ashush/delegates-in-C-Sharp/

Good luck!

Upvotes: 8

Related Questions