Since I start using event in c# I always want to know if it’s OOP oriented.
Let me explain. In Java, it had EventListner, Observer/Observable which object have to inherit to be able to fire an event or to listen to it . My point is, in Java, it have to be an object which have the responsibility to notify the subscriber or to do an action after being notify. In c#, all I see is :
public delegate void SomeHandler();
public event SomeHandler OnAction;
...
//somewhere in the firing class
OnAction();
...
//somewhere else in a subscriber class
_generateReport.ReportSubmited += someMethod;
private void someMethod()
{
//do some job
}
No class, only method and attribut…
So, is it OOP and if it is, how does it work?
Thanks !
The type responsible for holding a list of handlers is the
SomeHandlertype, which is a delegate type. You can build an instance of a delegate from an appropriate method, representing a call to that method… and you can combine delegates together to represent a sequence of calls.Think of events as language/platform support for the observer pattern, basically.
You should be aware of what events and delegates are like under the hood – see my article on them for some more details.
The non-OO part of this is that although delegates can be passed around like any other object, events can’t 🙁 You can use their reflection equivalent (
EventInfo) but it’s not quite the same thing…