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:
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:
var countDown = new CountDown(5);// Hook up event handlerscountDown.Tick = currentSecond => Console.WriteLine(currentSecond);countDown.Finished = () => ...
Get C# 4.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.