the keywords add and remove.....

This example comes from 'Implement Two Interfaces that Have an Event with the Same Name'

So far I can't find these keywords 'add' and remove' in the help docs. Were are they so I can understand what there are doing (well, just so I can understand there purpose and advantages).

event Delegate2 I2.TestEvent // explicit implementation of I2.TestEvent.
{
add
{
TestEvent2Storage += value;
}
remove
{
TestEvent2Storage -= value;
}
}

Thanks!...



Answer this question

the keywords add and remove.....

  • ptjhuang

    Basically the add/remove contextual keywords for an event are akin to the get/set contextual keywords for a property. They allow you to have explicit control over what happens when a consumer adds or removes themselves from an event.

    The following event declaration:



    public event EventHandler MyEvent;

     

    Is actually syntactic suger for the following:



    private EventHandler ClickEvent;
    public event EventHandler Click
    {
        [MethodImpl(MethodImplOptions.Synchronized)]  
        add
        {
             ClickEvent += value;
        }
        [MethodImpl(MethodImplOptions.Synchronized)]   
        remove
        {
             ClickEvent -= value;
        }
    }

     

    The [MethodImpl(MethodImplOptions.Synchronized)] attribute simply means that only a single thread can enter the add/remove methods at once.

    As you can see, the ClickEvent is the backing store of the event (basically holds the references to the consumers that hook up to the event), similar to the example you've shown above.



  • GavinRitchie

    Thanks for clearing this up for me!...
  • the keywords add and remove.....