Question

I have an interface with the line:

event EventHandler<MagazineEventArgs> MagazineChangedEvent;

When I implement the interface, Visual Studio generates the following template for me:

event EventHandler<MagazineEventArgs> IMagazineConfigView.MagazineChangedEvent
{
     add { throw new NotImplementedException(); }
     remove { throw new NotImplementedException(); }
}

However, I don't understand how exactly I should make use of these properties.

Was it helpful?

Solution

Often, you can just use a field-like event, e.g. just declare:

public event EventHandler<MagazineEventArgs> MagazineChangedEvent;

That's roughly equivalent to declaring a private delegate field and accessors which subscribe to it and unsubscribe from it:

private EventHandler<MagazineEventArgs> magazineChanged;

public event EventHandler<MagazineEventArgs> MagazineChangedEvent
{
    add { magazineChanged += value; }
    remove { magazineChanged -= value; }
}

... but the field-like event syntax provides some more thread safety. The exact nature of that thread safety depends on the version of C# you're using. From C# 4 onwards, they're a bit cleaner than they were - see the blog posts of Chris Burrows for more details (part 1, part 2, part 3, afterword).

You typically only need to implement the event yourself if you're doing something rather different - for example, chaining event subscription to a different underlying event, or to use EventHandlerList as a way of efficiently storing sparse subscriptions for a wide range of events.

It's important to understand how events and plain delegate fields differ - it's similar to the difference between properties and fields, although slightly more nuanced as events only have "subscribe and unsubscribe" operations, with no way of the caller raising them or determining other subscribers. See my article on the topic for more information.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top