-1

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

nabil
  • 904
  • 3
  • 12
  • 28

1 Answers1

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