Monday 25 March 2013

C# syntactic sugar - the event keyword

The event keyword is a great example of syntactic sugar. The following class definition
    public class Button
    {
        public event EventHandler Pushed;
    }
results in the following code being generated
    public class Button
    {
        private EventHandler _pushed;

        public event EventHandler Pushed
        {
            add
            {
                EventHandler eventHandler = this._pushed;
                EventHandler comparand;
                do
                {
                    comparand = eventHandler;
                    eventHandler = System.Threading.Interlocked.CompareExchange<EventHandler>(ref this._pushed, comparand + value, comparand);
                }
                while (eventHandler != comparand);
            }
            remove
            {
                EventHandler eventHandler = this._pushed;
                EventHandler comparand;
                do
                {
                    comparand = eventHandler;
                    eventHandler = System.Threading.Interlocked.CompareExchange<EventHandler>(ref this._pushed, comparand - value, comparand);
                }
                while (eventHandler != comparand);
            }
        }
    }
In .Net, an event is a special type of multicast delegate which can only be invoked from the class or struct where it is declared. Any number of subscriptions can be added to the event, which will be called in order when the event is raised.

The add and remove blocks that manage event subscriptions are generally auto-implemented, but they can easily be overridden. As you can see from the code above, the compiler-implemented code uses the System.Threading.Interlocked.CompareExchange method to guarantee thread safety around the adding and removing of subscriptions.

No comments:

Post a Comment