0

I've been been studying event systems in C#, so I do understand why you can't directly access the subscribers of an event. (I started with delegates, went through anonymous functions and lambda statements). I then came upon the problem of managing the subscriptions when implementing my first system. I am VERY green here.

As usual Stackoverflow is very helpful. This question shows me how to make a function to clear all the subscribers. For my purposes, this will be specific enough (clear all and assign new as desired).

How might I inform a single function to clear one of several event delegates?

public delegate void AnEventHandler(object sender, EventArgs e);

public class EventPublisher :
{
    public event AnEventHandler GroupA;
    public event AnEventHandler GroupB;

    public void ClearSubscribers(AnEventHandler handlerToClear)
    {
        handlerToClear = null;
    }
}

I thought I could write it like this, and my subscribing class could simply do

(EventPublisher MyPublisher)

MyPublisher.ClearSubscribers(MyPublisher.GroupA);

But alas it informs I can only use that with the += or -= operator, which surprised me a bit because I thought a reference would be acceptable.

I also do intend to implement my own add() and remove() functions. The thing about that is, it has the same problem: I need 6 event handlers. Surely I don't need to write 6 parallel nullification function and 6 unique pairs of add/remove functions? My brain is thinking inheritance but dots aren't connecting.

Community
  • 1
  • 1

1 Answers1

-1

If you can afford to, setting a variable to null will remove it's variables, then just re-set it.

Otherwise you should be able to do it this way.

Community
  • 1
  • 1
stisch
  • 30
  • 4
  • The question is how to write one function that can null a chosen one of several events from outside the publishing class. –  Dec 31 '16 at 03:24
  • This does not answer the question asked. It's unlikely for you to gain 50 reputation to get the *Comment Everywhere* privilege, if you continue to ignore this site's rules. See [answer] for more information. – IInspectable Dec 31 '16 at 12:53
  • I would like to add that I found several ways around this issue. FIrst, you could just use a delegate, which lacks the problem protections of an event. Second, you could override the += and -= operators of the event to prevent the need for such a function (although this is considered bad practice because the consumer may not know about the override). Third, you could write a function inside the publishing class for each event that needs this capability. This seems like it should be possible, and the question is purely academic. I changed the structure of my program so that it is not necessary. –  Dec 31 '16 at 18:06