O'Reilly logo

C# 5.0 Unleashed by Bart De Smet

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

add and remove Accessors

With events based on a piece of metadata pointing at two methods, it shouldn’t be at all surprising that C# provides a way to customize those methods in case you want to do so. In the context of events (and properties), we refer to those methods as accessors. For events, two accessors exist called add and remove. The syntax is predictable, being analog to get and set for properties:

public event Finished {
    add {
        // Called when doing +=.
    }
    remove {
        // Called when doing -=.
    }
}

Inside those accessors, the right side of the += and -= operator is available using the value keyword. This is similar to the way a property setter gets access to the value being assigned to it.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required