Things I Didn't Know About C# Part 1: Events vs. Delegates

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments

Would've been more useful if it explained why it worked like this.

What the event keyword actually does is compile into something like

private EventHandler Foo;
public void add_Foo(EventHandler delegate) => Foo += delegate;
public void remove_Foo(EventHandler delegate) => Foo -= delegate;

That'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.

👍︎︎ 17 👤︎︎ u/tweq 📅︎︎ Aug 25 2017 🗫︎ replies

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, but event 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.

👍︎︎ 8 👤︎︎ u/FizixMan 📅︎︎ Aug 25 2017 🗫︎ replies

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.

👍︎︎ 6 👤︎︎ u/spacemoses 📅︎︎ Aug 26 2017 🗫︎ replies
👍︎︎ 1 👤︎︎ u/ellison11 📅︎︎ Aug 26 2017 🗫︎ replies

Another interesting fact about events is that events have add and remove accessors.

for example

void Main()
{
    var bar = new Bar();
    bar.EvBar += (s, e) => "Yey".Dump();
    bar.Start();
}
public class Foo
{
    protected event EventHandler EvFoo;

    public void Start()
    {
        EvFoo?.Invoke(this, EventArgs.Empty);
    }
}
public class Bar : Foo
{
    public event EventHandler EvBar
    {
        add
        {
            base.EvFoo += value;
        }
        remove
        {
            base.EvFoo -= value;
        }
    }
}
👍︎︎ 1 👤︎︎ u/AndreiAbabei 📅︎︎ Aug 28 2017 🗫︎ replies
Captions
all right so welcome back to the channel guys and gals and what is to be the first episode of a little series I'm calling things I didn't know about c-sharp so I'll be doing short videos focusing on some particular little feature of the language that I find to be odd weird or just funny or perhaps just lesser-known and we'll be starting off by comparing events and delegates and I thought I had Delhi it's pretty much down but a student asked me a question and I was like no that's not gonna work and he said are you sure and I said yeah I think so let's find out and it turned out he was absolutely right so let's have a look okey dokey so let's have a look at my boomer class here so the boomer class exposes an a boom event based on the event handler delegate you all know it object event arcs it has a method called start which calls on boom three times and that thing all it does is fire the event and I'm using the Elvis operator here not to not have to do an explicit knowledge check basically so let's head over to the program and see what it's doing so I'm creating an instance of boomer hooking up the boom event to my event handler writing out boom on the console and then basically starting so if I run this program we should get boom boom boom so the question now is if I go into boomer here what happens if we instead of exposing this event based on the event handler delegate instead of doing that we'll just expose the delegate as a public field something like this so it might surprise some of you that this still compiles it still works so if I run it to still get boom boom boom so it's interesting to note not everyone knows that the plus equals operator is available for delegates as well so we can do something like action a equals let's write out something on the console and I'll do a plus equals and add a question mark here so have an exclamation mark and a question mark and then let's invoke the delegate so if I run this I actually get the exclamation mark and the question mark so the plus equals operator is not exclusive to events just so we get that out of the way now doing it this way with the public field we know that's disgusting of course public fields are evil but let's see how it differs from events so now that it's a public field I can do something like this I can go boomer boom and basically invoke it so I can go and say yeah around that thing for me invoke the delegate so now we're looking at four booms so basically events would stop me from doing this event would guarantee that boom can only be raised from within the clause that exposed it I can also even scarier this stuff like boomer dot boom equals not and I just set it to a new value and this is fine so if I was to swap these rows we would get an exception here on this line so that's kind of nasty so of course we don't want any of that so if we go back to the boom and just say event it's let put the event keyword back we should get compile time errors here so they're fairly specific the message says boomer dog boom can only appear on the left-hand side of a plus equals or minus equals except when used from within the type Boomer so those are the kinds of shenanigans that this little keyword is stopping us from and that's basically it that's basically everything that is doing of course it's worth to note also that events are fine in interfaces and delegates or not so I could basically do an interface ifou and do something like event event handler boom one and that's fine but I could not do something like this just expose basically a field interfaces kind of contained fields so that's another difference between events and delegates so I hope some of you was found this interesting that this little keyword really does very very little for us okay so thanks guys and have a great day and I'll see you in a week with another interesting little topic of something I didn't know about c-sharp all right have a good one
Info
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
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.