Re: Clone without copying event handlers

Tech Tip: Click here to run a free scan for Windows Errors and optimize PC performance



John Yale wrote:
> I am cloning an object using MemberwiseClone plus some code of my own to
> perform a deep copy. This is fine except MemberwiseClone copies event
> handlers which I don't want.
>
> How can I remove all event handlers from an object? This needs to be done
> from within the object itself. RemoveHandler is not an option as I have no
> knowledge of what handlers have been installed.
>
> I have seen posts sugesting something like:
>
> [Delegate].RemoveAll(ChildAddedEvent, ChildAddedEvent)
>
> where my event is called 'ChildAdded'
>
> This seems on the right lines and although it compiles, it does not have
> the required effect. Ideally I would like to remove all event handlers
> attached to the object without having to name them individually.

Hi John,

I've done this before:

If Not InstanceAddedEvent is Nothing Then
For Each rb as System.Delegate in
InstanceAddedEvent.GetInvocationList()
RemoveHandler
InstanceAdded,DirectCast(rb,InstanceAddedEventHandler)
Next
End If

(If you want C# instead, it shouldn't be very difficult to adapt)

And it seems to work for me.

Damien

.