Please show me simple example why do we need it and what will happen if we didn't use it in the example with delegate. Thank you
Asked
Active
Viewed 137 times
-1
-
possible duplicate of [Why do we need the "event" keyword while defining events?](http://stackoverflow.com/questions/3028724/why-do-we-need-the-event-keyword-while-defining-events) – George Duckett Jan 25 '12 at 15:24
-
2@GeorgeDuckett oh you managed to find sense out of this question. Kudos. – Louis Kottmann Jan 25 '12 at 15:25
-
are you asking for the difference between the event and the delegate keyword? – mtijn Jan 25 '12 at 15:25
-
@OlivierJacot-Descombes: I think he wants an example (like in Jon's answer). – George Duckett Jan 25 '12 at 15:28
1 Answers
8
Sure:
// With events...
public class Button
{
public event EventHandler Click;
}
public void Client
{
public void Method(Button button)
{
// This is all I can do...
button.Click += SomeHandler;
}
}
// With plain delegate fields or properties...
public class Button
{
public EventHandler Click { get; set; }
}
public void Client
{
public void Method(Button button)
{
// Who cares if someone else is already subscribed...
button.Click = SomeHandler;
// And let's just raise the event ourselves...
button.Click(button, EventArgs.Empty);
}
}
In other words, with events you've got a controlled implementation of the pub/sub pattern - separate subscribers can't interfere with each other (except perhaps by throwing an exception within their handler) and only the publisher can "publish" (call the handlers).

Jon Skeet
- 1,421,763
- 867
- 9,128
- 9,194