Using .NET Events
Events are just delegates in disguise but provide additional levels of protection against the attacks we’ve seen previously. Syntactically, very little has to change:
class CountDown { private uint _seconds; public CountDown(uint seconds) { _seconds = seconds; } public event Action<uint> Tick; public event Action Finished; public void Start() { ... }}
See the difference? Instead of Tick
and Finished
being declared as properties with a delegate type, we now use the event
keyword instead and drop the get
and set
property accessors. (You’ll see later how events have optional accessors called add
and remove
.)
At the use site, we can no longer write the following: ...
Get C# 5.0 Unleashed now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.