0

I've been playing around with anonymous functions and delegates. It's left me wondering what advantages the traditional ways of declaring events have.

Consider this inside of a class.

public delegate void MyHandler(string input);
public MyHandler OnSomethingHappens;

// ...then, somewhere else
OnSomethingHappens("The thing that happened...");

From outside the method...

MyClass.OnSomethingHappens += (input) => { Console.WriteLine("Do something"; };
MyClass.OnSomethingHappens += (input) => { Console.WriteLine("Do something else"; };

How is this any different than a traditional event handling situation, where I code up a SomethingHappensEventArgs class, wire it to an actual event, etc.?

With the code above, I am able to assign code to execute when the class says something has happened...which is essentially what an event does.

Why would I go to all the trouble of creating a "true" event? Dare I say it...Intellisense icons? :-)

Deane
  • 8,269
  • 12
  • 58
  • 108
  • Mainly so others can't clear out everyone wired up to the event already - [Similar question](http://stackoverflow.com/questions/3028724/why-do-we-need-the-event-keyword-while-defining-events) – Jonesopolis Oct 14 '15 at 20:50

2 Answers2

2

With your approach, any object can clear the delegate:

MyClass.OnSomethingHappens = null;

or invoke it:

MyClass.OnSomethingHappens();

Events only allow other objects to add/remove delegates.

Jakub Lortz
  • 14,616
  • 3
  • 25
  • 39
-1

if you declare OnSomethingHappens as public event

public MyHandler OnSomethingHappens;

you'll be able to do only the += and -= opertors if you keep it public you can assign it null from outside the class

Liam
  • 27,717
  • 28
  • 128
  • 190
ro-E
  • 279
  • 1
  • 5
  • 16