delegate instance is passed by value@@

myEvent += myDelegate;

Q: Is myDelegate passed by reference?
A: No. member-wise copying. In other words, each item in the delegate inv list is passed in (by reference?).
A: No. The invocation list (say 2 callbacks) are appended to myEvent’s internal inv list, and new list is ReBound to myEvent internal delegate variable.

That’s a short answer. For the long answer, we need to forget events and callbacks and focus on pure delegates as list objects holding simple “items”. Suppose dlg1 variable points to address1, and dlg2 points to address2.

dlg1 += dlg2 // translates to
dlg1 = Delegate.Combine(dlg1, dlg2). // Note: re-binding dlg1

Now dlg1 points to newly allocated address11. At this address there’s a new-born delegate object whose inv list is

[item1 at addr1,
item2 at addr1 …
itemN at addr1,
item1 at addr2,
item2 at addr2, ….
itemM at addr2]

According to http://msdn.microsoft.com/en-us/library/30cyx32c.aspx, some of the items could be duplicates — Legal.

30 seconds after the Combine() operation, suppose dlg2 is subsequently modified (actually re-bound). Instead of 2 callbacks at addr2, variable dlg2 [1] now points to addr22 with 5 callbacks. However, this modification doesn’t affect the inv list at addr11, which dlg1 now points to.

Therefore, we can safely say that in a Combine() operation the RHS delegate’s inv list is copied-over, passed by value or “pbclone”.

[1] like all java reference variables, a c# delegate variable is a 32-bit pointer object. As explained in
http://bigblog.tanbin.com/2012/03/3-meanings-of-pointer-tip-on-delete.html, the compiler is likely to allocate 32 bit of heap for this 32-bit object.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s