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 O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.