Things I Didn't Know About C# Part 1: Events vs. Delegates
Video Statistics and Information
Channel: Pontus Wittenmark
Views: 21,374
Rating: undefined out of 5
Keywords: pontus wittenmark, events vs delegates, events, delegates, Things I didn't know about C#
Id: el-kKK-7SBU
Channel Id: undefined
Length: 5min 44sec (344 seconds)
Published: Fri Aug 25 2017
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.
Would've been more useful if it explained why it worked like this.
What the
event
keyword actually does is compile into something likeThat's why events can only be invoked from within the class they're declared on, the actual delegate is private and external code can only call the add/remove methods.
Another difference is that (unlike the code I posted), the implementations of the add/remove methods are thread-safe. If you just have a public delegate field and multiple threads modify it at the same time, one thread may overwrite another thread's invocation.
And while interfaces can't contain can't contain fields (of any type), they could of course have a delegate properties.
Couple bits.
At 4:40, you mention that the aspects you pointed out is everything that the
event
keyword is doing. It's largely correct, butevent
also adds some level of thread safety to adding/removing listeners to the event.More importantly, it also enables the use of custom event add/remove accessors. This is a pretty significant distinction.
You then go on to claim that you cannot use delegates in interfaces because it's a field. But for the most part, you could have just redefined your field to be an auto-property and it would work just fine.
In theory, the
event
keyword might also be leveraged in reflection or the designer to control some application or IDE behaviour.The other items were on point in that, the big reason to use
event
is typically to have control over reassignment and invocation.I was not aware you could do += to add to an Action variable.
When you invoke the Action, is it running two different methods, or does the += somehow append the second instruction to the first? I'm guessing the first, but then it would seem like the type would change to IEnumerable<Action>.
This is making me uncomfortable.
Some good supplemental information here
Another interesting fact about events is that events have add and remove accessors.
for example