views:

61

answers:

2

Hi Guys,

I want to know how do I go about removing individual delegates from the invocation list of the parent delegate.

<DelegateName>.RemoveAll();

Now I can just remove all and that will work just to get the idea in motion and see if works which it should but then any delegates removed will need adding again at RunTime!!!

so: ...

foreach(Delegate d in <DelegateName>.getInvocationList)
{ // do something with 'D'?? }

Now that I have access to 'D' I can drop it into a .Remove() but it requies two arguments??? Could I get some help with this please?

Lastly, once the delegate has been removed, what is the best way to re-add it again? So i'm assuming Reflection might play a part in this but over to you guys.

UPDATE:

Essentially there is a global delegate that has many events living in different winforms classes that are instances of it. All of these events have a handler that handles the event when it is fired. The delegate all the way at the top governs all handlers that match its signature are fired. I want to mess about with this delegate at the top, I want to remove all handlers and then re-add them at run time. So the delegate at the top is a multicast delegate and its invocation list is a list of individual delegates that in turn point to one of the four handlers that I have added. I hope that makes sense, thats a general idea of whats I am doing.

+5  A: 

You can't - delegates are immutable. You can create a new delegate which is equivalent to the old one without certain actions, but you can't modify the existing one in-place.

Jon Skeet
thanks Jon, I just read that last night but can't we use the binary operators '-=' or '+=' to add and remove delegates from invocation list? It's a just a thought ...
IbrarMumtaz
@IbrarMumtaz: No, those don't change the existing delegates - they return a new delegate based on the old one.
Jon Skeet
+3  A: 

Invocation list is internal piece of delegate, you can't modify it normally. You may be able to do it by very dirty reflection, but i don't think that it is valid idea for production code. But there is another way to solve it validly. You can define event without automatic underlaying delegate and control the invocation list yourself. For that you need to define event with explicit add and remove keywords, see here. You will have to reimplement some stuff for that but it will give you full control.

Andrey