3

I have a question about Routed Events, I see in some documentation that when we define our own custom events, we add and remove handlers to it using the following code:

public event RoutedEventHandler CustomClick
{
    add { AddHandler(CustomClickEvent, value); }

    remove { RemoveHandler(CustomClickEvent, value); }
}

But my point is that this is neither looking like a Constructor syntax, nor a Property initialization syntax! also it is not a property get/set syntax (although it looks similar to that). I have read detailed C# documentation, but I don't see what kind of construct is this. Only in documentation about custom RoutedEvents, i see this code, but in normal C# tutorial/primer, I never see that this is a legal language construct. Can anybody explain to me this? or point me to a good documentation explaining this?

Thanks in advance.

Ant P
  • 24,820
  • 5
  • 68
  • 105
user2755525
  • 219
  • 2
  • 3
  • 14

2 Answers2

2

They are "event accessors". They are the event equivalent of property syntax. They allow you to expose an event and change how it works .. without breaking the encapsulating classes contract (like properties).

See here for an explanation: http://msdn.microsoft.com/en-us/library/bb882534.aspx

Simon Whitehead
  • 63,300
  • 9
  • 114
  • 138
0

That's a syntax that's reserved for events in C#, see also here. To quote:

The add contextual keyword is used to define a custom event accessor that is invoked when client code subscribes to your event. If you supply a custom add accessor, you must also supply a remove accessor.

sinelaw
  • 16,205
  • 3
  • 49
  • 80
  • Ok, so this means that 'add' keyword is same as '+=' operator for subscribing a method to an event? and similarly, 'remove' corresponds to a '-=' (unsubscribe) operator... correct? – user2755525 Dec 18 '13 at 22:58
  • `add` specifies what to *do* when someone uses `+=`. By the way it's available at least since VS2008. [**This answer**](http://stackoverflow.com/questions/3028724/why-do-we-need-the-event-keyword-while-defining-events) discusses events in more detail. – sinelaw Dec 18 '13 at 23:10