Events are an implementation of the observer pattern.
An event is implemented as a list of methods that are called when a valve is raised.
Delegates are method references: unlike Java, C # offers a method reference method.
It’s not a priori better to use events than to implement an observer pattern. But events offer a fairly general way to do this, and in many cases are highly optimized for this task, thus providing a more efficient and convenient way to organize this.
The delegate is determined by the signature of the expected method. For instance:
public delegate void FooMethod (Bar x, Baz y);
You define a delegate for the void
methods given Bar
and a Baz
. Therefore, if you have an instance of the following class:
public class Qux { public void Method (Bar x, Baz y) {
Then you can refer to the method:
Qux q = new Qux(); FooMethod fm = q.Method;
An event
, therefore, is a delegate
list with the same signature:
You define the event as:
private event FooMethod SomeEvent;
You can add delegate
(listeners) using the +=
operator:
SomeEvent += q.Method;
remove the delegate with the -=
operator and raise the event with:
SomeEvent(new Bar(), new Baz());
It is as if you are calling one method that dispatches.
By calling event
, all registered delegate
will be called in the registration order.
Note : calling SomeEvent(new Bar(), new Baz());
, this does not mean that each delegate receives new
instances: instances are first created and divided into all delegate calls.
Conclusion I think the C # developers did a great job with observer patterns, as the programmer is no longer responsible for the correct programming. In addition, events are easy to understand and use convenient syntax. In special situations, however, programmers may need to implement the observer himself. But these are very rare cases.