One minute
Several Facts about C# Events and Delegates
Here I put some facts about events and delegates.
Event vs. Delegate
- “event” in delegate definition is just a limitation of delegate invocation. If you use “event” you can invoke the delegate from the scope of the class ONLY. Usually you would not like a client of your class to directly trigger an event. Use “event” to encapsulate your delegates.
- Interfaces define public methods and properties of the class. Interface does not define member variables. In order to specify a delegate in an interface an “event” modifier should be used.
- “event” also provides an ability to perform some actions when something is subscribed or unsubscribed from the delegate. For that purpose “add” and “remove” accessors should be used inside the definition of an event (just like get/set accessors in a regular property).
Duplicate Subscription
- Duplicate subscription to events results in duplicate invocation of subscribed method.
“MyEvent += Function” vs. “MyEvent += new Handler(Function)”
- This syntax produces the same result. In both cases a “Function” is subscribed to “MyEvent”.
“MyEvent -= Function” vs. “MyEvent -= new Handler(Function)”
- This syntax produces the same result. In both cases a “Function” is unsubscribed from “MyEvent”.