Everyone knows that a private event handler can listen to an event from another class. (In the examples in the documentation, only private handlers are always used.)
An event handler is nothing more than a private method in another class than the calling event. Therefore, calling the handler from outside its class interrupts the encapsulation. Or am I missing something?
Sample code for completeness:
class Caller { public event EventHandler MyEvent; public void RaiseMyEvent() { MyEvent(this, EventArgs.Empty); } } class Receiver { private void MyPrivateHandler(Object sender, EventArgs e) { Console.WriteLine("I'm a private method!"); } public void Subscribe(Caller caller) { caller.MyEvent += this.MyPrivateHandler; } }
and after subscribing receiver.Subscribe(caller); we can comfortably call a private method in the receiver class from the outside: caller.RaiseMyEvent(); .
This is a purely academic question, even a scholastic one. Moreover, I personally find this feature very convenient, practical and actually love it. This is really great: we can directly give other classes the right to call our private methods. (We can also not sign it and do many exciting things with delegates and events.) In any case, it still violates the encapsulation cleanliness ... or not?
PS: Thanks to Matthew Watson for pointing out the following nuance: when subscribing to an event, a private handler can be called exclusively by this event. Although if we make it public (or invoked through the public wrapper method), it can be called by anyone. This is a pretty big difference in availability.
PPS: And yes - I have never seen this problem mentioned in a textbook. If you know one, please leave a link.
source share