8

Can someone explain to me how custom event accessor works? I have read a couple of articles on google but still could not understand. Also, when to use it?

I have the following code snippet from my project. If someone can explain this to me it would be really great.

private event Action<int> ActivityChanged = delegate {};

event Action<int> IActivityFacade.ActivityChanged
{
    add
    {
        ActivityChanged += value;
        value(GetSelectedActivity()); 
    }
    remove { ActivityChanged -= value; }
}
Kevin
  • 16,549
  • 8
  • 60
  • 74
App
  • 346
  • 3
  • 9

1 Answers1

4

Without knowing exactly what part of the existing documentation and other references regarding custom event accessors it is specifically that you don't understand, it's impossible to know for sure what answer you're looking for.

A C# event is simply an add and a remove method (similar to a property's get and set methods). The compiler provides a default implementation for these methods, but if you have custom behavior you want to implement yourself, you can write the methods yourself. In your example, which is not thread-safe by the way, the custom accessors are apparently there so that a newly subscribed delegate is invoked as soon as it's added.

If you need more details than that, please improve the question so that it's clear what it is specifically about custom event accessors that you are having trouble understanding. Be sure to explain exactly what you do understand and what documentation you've already referenced, so that we can avoid excessively long answers that waste time on aspects you already know about.

Peter Duniho
  • 68,759
  • 7
  • 102
  • 136
  • 2
    Do custom accessors need to provide the default implementation features which are event subscribe and event unsubscribe in addition of custom features? Or do custom accessors automatically inherit these features which are required anyway? The example provided in the question seems to favor the first assumption, but if this is the case, [how can this code, without default subscribe/unsubscribe work](https://i.stack.imgur.com/vHVZO.png)? – mins Jun 02 '19 at 08:38
  • 2
    @mins: The former. Event accessors work just like property accessors. If you declare your own instead of relying on the default implementation, you have to do _everything_. Typically this does mean you have to replicate the default behavior, i.e. accept a delegate on add which is later invoked when the event is raised, and discard your reference to that delegate on remove and ensure that it's not invoked. But just as properties can deviate from their normal behaviors, events could too, depending on your needs. Do so at your own risk (i.e. almost always, they shouldn't). :) – Peter Duniho Jun 02 '19 at 17:29