Anonymous Methods & Object Events  
Author Message
Robert F Bouillon





PostPosted: Visual C# General, Anonymous Methods & Object Events Top

I never did like how I HAD to hook an event to a class method signature. If I wanted to hook an event to an object instance within a function, that I only needed in that function, I had to create an event handle in the class.

Thanks to anonymous methods, I can create my event handler body in an anonymous method from within my code. The problem is that I don't know how to 'unhook' the handler from the event, because the even doesn't expose the multicast delegate.

psuedo-code:

[code language=C#]

form_OnClick(...)
{
Something s = new Something();
s.SomeEvent+=delegate(object sender, EventArgs e){this.a = e.a;};
{...}
s.SomeEvent.Clear()
//How do I do this
{...}
}

[/code]

Thanks.



Visual C#4  
 
 
Paul Louth





PostPosted: Visual C# General, Anonymous Methods & Object Events Top

You can either null the event, or if you know the order that the delegate was added then you can use the index in the invocation list:

SomeEvent -= (SomeDelegate)SomeEvent.GetInvocationList()[index];

 


 
 
Keith Rome





PostPosted: Visual C# General, Anonymous Methods & Object Events Top

If it is simply a regular property with type equal to a delegate, then the invocation list can be manipulated in that fashion... but if it was decorated with the "event" keyword, then if my memory is correct, the runtime will not allow you to reach in and mess with the invocation list from anything but the declaring class.

For the original poster - I don't think you can do this. The trade-off with anonymous delegates is that they are indeed, anonymous. In order to remove from the multicast invocation list, the runtime needs to know both the method ptr and the method's host instance. An anonymous delegate has only the latter (implicit).

HTH