6

In C# Is there a fundamental difference between using

event EventHandler<myeventargs> and EventHandler<myeventargs> As they both produce the same effect from what I can see apart from using the event keyword gives you a different icon in intellisense.

LeonH
  • 1,039
  • 2
  • 22
  • 45
Trey
  • 63
  • 3
  • possible duplicate with http://stackoverflow.com/questions/3028724/why-do-we-need-the-event-keyword-while-defining-events – nevets Aug 19 '14 at 11:52
  • 1
    There is, same difference as between a field and a property. If you don't use the *event* keyword and expose the delegate object directly then any code can do nasty things like setting it back to null. – Hans Passant Aug 19 '14 at 13:14

1 Answers1

6

They seems to be alike, but really different.

With event keyword, you are making them something like properties, which means you can register them in public, while maintain a private back-end.

However, without event keyword, it's just a public delegate field, and anyone can remove or modify others' events, which is a "encapsulation disaster" as @Jonskeet said.

Check this article by Jon Skeet, it's very helpful :)

Edit:

What I summarized above was not my original thinking, all credits to @Jonskeet's post.

Community
  • 1
  • 1
nevets
  • 4,631
  • 24
  • 40
  • 2
    Why don't you just provide the link of another post that mentions about [encapsulation disaster](http://stackoverflow.com/questions/3028724/why-do-we-need-the-event-keyword-while-defining-events) ? – Yuliam Chandra Aug 19 '14 at 10:39
  • 1
    I thought a brief summary is better a dull link, but it's my fault not to put the link in. – nevets Aug 19 '14 at 11:53