The keyword event was explicitly invented so that you do not do what you want. It restricts access to the base delegate object, so no one can directly interact with subscribers to the event handlers that it stores. Events are accessories for the delegate, just as a property is an accessory for the field. The property allows only receiving and installing, the event only allows adding and removing.
This protects your code, and other code can only remove the event handler if it knows the event handler method and the target. C # language adds an extra layer of security by not letting you name the target.
And WinForms adds an extra layer of security, so it becomes difficult even if you use Reflection. It stores delegate instances in EventHandlerList with a secret cookie as a key, you need to know cookies in order to dig an object from the list.
Well, donβt go there. It is trivial to solve your problem with a little code at your end:
private bool mSubscribed; private void Subscribe(bool enabled) { if (!enabled) textBox1.VisibleChanged -= textBox1_VisibleChanged; else if (!mSubscribed) textBox1.VisibleChanged += textBox1_VisibleChanged; mSubscribed = enabled; }
Hans Passant Apr 23 '10 at 10:07 2010-04-23 10:07
source share