How to: Implement Custom Event Accessors (C# Programming Guide) Home
This page is specific to:.NET Framework Version:3.54.0
C# Programming Guide
How to: Implement Custom Event Accessors (C# Programming Guide)

An event is a special kind of multicast delegate that can only be invoked from within the class that it is declared in. Client code subscribes to the event by providing a reference to a method that should be invoked when the event is fired. These methods are added to the delegate's invocation list through event accessors, which resemble property accessors, except that event accessors are named add and remove. In most cases, you do not have to supply custom event accessors. When no custom event accessors are supplied in your code, the compiler will add them automatically. However, in some cases you may have to provide custom behavior. One such case is shown in the topic How to: Implement Interface Events (C# Programming Guide).

Example

The following example shows how to implement custom add and remove event accessors. Although you can substitute any code inside the accessors, we recommend that you lock the event before you add or remove a new event handler method.

event EventHandler IDrawingObject.OnDraw
        {
            add
            {
                lock (PreDrawEvent)
                {
                    PreDrawEvent += value;
                }
            }
            remove
            {
                lock (PreDrawEvent)
                {
                    PreDrawEvent -= value;
                }
            }
        }

See Also

Reference

Community Content

Code sample update for newer C# compilers
Added by:Austin Donnelly MSFT

You may get the error:

The event 'IDrawingObject.OnDraw' can only appear on the left hand side of += or -=

This is because newer C# compilers no longer generate the underlying field which represents the backing store for the event. You need to do this yourself:

  private EventHandler _onDrawHandler;
  public event EventHandler IDrawingObject.OnDraw
  {
      add { _onDrawHandler = (EventHandler)Delegate.Combine(_onDrawHandler, value) }
      remove { _onDrawHandler = (EventHandler)Delegate.Remove(_onDrawHandler, value) }
  }

NOTE: this is not thread-safe, whereas the previous compiler-generated events were.

© 2009 Microsoft Corporation. All rights reserved.   Terms of Use | Trademarks | Privacy Statement
Page view tracker
Rate the Lightweight library
x
Lightweight builds on ScriptFree (loband) by adding features you've requested: a SearchBox and default code language selection.
Do you like the SearchBox?
Do you like the tabbed code blocks?
How useful is this topic?
Tell us more.
Thanks
x
You're helping to improve MSDN Online.
Feedback
Switch View
Classic
Lightweight Beta
ScriptFree
Switch View