How do I unsubscribe all handlers from an event for a particular class in C#?

.net, c#, events

Solution

Each delegate has a method named `GetInvocationList()` that returns all the actual delegates that have been registered. So, assuming the delegate Type (or event) is named say `MyDelegate`, and the handler instance variable is named `myDlgHandler`, you can write:

Delegate[] clientList = myDlgHandler.GetInvocationList();
foreach (var d in clientList)
       myDlgHandler -= (d as MyDelegate);

to cover the case where it might be null,

 if(myDlgHandler != null)
  foreach (var d in myDlgHandler.GetInvocationList())
       myDlgHandler -= (d as MyDelegate);

Problem

Basic premise: I have a Room which publishes an event when an Avatar "enters" to all Avatars within the Room. When an Avatar leaves the Room I want it to remove all subscriptions for that room. How can I best unsubscribe the Avatar from all events in the room before I add the Avatar to a new Room and subscribe to the new Room's events? The code goes something like this: ``` class Room { public event EventHandler<EnterRoomEventArgs> AvatarEntersRoom; public event EvnetHandler<LeaveRoomEventArgs> AvatarLeavesRoom; public event EventHandler<AnotherOfManyEventArgs> AnotherOfManayAvatarEvents; public void AddPlayer(Avatar theAvatar) { AvatarEntersRoom(this, new EnterRoomEventArgs()); AvatarEntersRoom += new EventHandler<EnterRoomEventArgs>(theAvatar.HandleAvatarEntersRoom); AvatarLeavesRoom += new EventHandler<EnterRoomEventArgs>(theAvatar.HandleAvatarEntersRoom); AnotherOfManayAvatarEvents += new EventHandler<EnterRoomEventArgs>(theAvatar.HandleAvatarEntersRoom); } } class Avatar { public void HandleAvatarEntersRoom(object sender, EnterRoomEventArgs e) { Log.Write("avatar has entered the room"); } public void HandleAvatarLeaveRoom(object sender, LeaveRoomEventArgs e) { Log.Write("avatar has left room"); } public void HandleAnotherOfManayAvatarEvents(object sender, AnotherOfManyEventArgs e) { Log.Write("another avatar event has occurred"); } } ```

Original source

Related problems