[C#] Delegates and Events (E01: delegates)

Поделиться
HTML-код
  • Опубликовано: 25 авг 2024
  • In this two-part series we'll be looking at delegates and events.
    This episode covers how delegates can be used to pass methods as arguments into other methods. It also very briefly touches on lambda expressions.
    The next episode can be found here:
    • [C#] Delegates and Eve...
    If you'd like to translate this video, you can do so here: www.youtube.com...
    If you'd like to support these videos, you can make a recurring monthly donation (cancellable at any time) through Patreon: / sebastianlague
    Or a once-off donation through PayPal:
    bit.ly/SupportG...

Комментарии • 182

  • @TheAxeForgetsTheTreeRemembers
    @TheAxeForgetsTheTreeRemembers 7 лет назад +74

    6:50 Magic happening :D.
    Love when people explain by simply showing how it works, how we do without, and it's much better with.
    This way you not only understand quicker, but you actually want to use the feature.
    Excellent video.

  • @uzferry5524
    @uzferry5524 7 лет назад +176

    this is the quickest yet most understandable tutorial i've found

    • @FuzzyDPozzy
      @FuzzyDPozzy 5 лет назад +2

      the same @sebastian is the beast!!!

    • @bobsagget823
      @bobsagget823 5 лет назад +8

      No it is not. What IS a delegate?
      Nobody knows after watching this video. Useless.

    • @xrcryptodev
      @xrcryptodev 4 года назад +2

      @@bobsagget823 I had a hard time understanding it, but I eventually did. He teaches really fast at times, so the more experience you have, the better. But yeah if I were a beginner this would fly far above my head.

    • @klarnorbert
      @klarnorbert 4 года назад

      Would have been better an example with an event system. For example, when you click a button on UI, you turn all gameobjects to a random color which are subsribed to the event.

  • @FesliyanStudios
    @FesliyanStudios 7 лет назад +42

    in other words, delegates are simply reference variables. They hold any number of methods as a reference (as long as the signatures match)

  • @typedef_
    @typedef_ 7 лет назад +27

    For those who are familiar with C, creating a delegate type is the same as creating a typedef for a function pointer. When declaring a delegate, you essentially declare a pointer of that type and assign the function address to it. When invoking a delegate, you indirectly call the function using the pointer. This of course lets you create arrays of delegates making for fast decoding and program flow. You can also have delegates "pointing" to array of delegates making for even more complex decoding.

    • @algot34
      @algot34 2 года назад +1

      Thank you

  • @AlexeyFilippenkoPlummet
    @AlexeyFilippenkoPlummet 4 года назад +1

    The only good video about delegates I found on YT. Everyone else is too busy gibbering the way they understood this concept instead of actually explaining it with clear examples. Good job.

  • @DavidB-rx3km
    @DavidB-rx3km 4 года назад +73

    I found a fault in your video.
    You didn't introduce yourself with a 'HEEEEEYYY WHAT'S UP GUYS, THIS IS SEB, MY PATREON SUBCRIBE LIKES' etc

    • @MZ-uv3sr
      @MZ-uv3sr 4 года назад +2

      THANK GOD. Was tempted and decided ya know what...the 50 ish minutes he saved me by explaining clearly in 7 minutes instead of an hour with no HEY! WHAT"S UP hyper stuff is worth $5 right there. One time patreon x => x+5

  • @gonderage
    @gonderage 3 года назад +2

    I'm still trying to wrap my head around delegates, but I think you've explained them enough for me to try on my own. Thanks again for a wonderful tutorial, Sebastian!!!

  • @ryanisthewind
    @ryanisthewind 2 года назад +3

    Teaching is a talent. thats why Sebastian's videos are so wonderful. he is a great teacher.

  • @filmihaylov356
    @filmihaylov356 8 лет назад +26

    It was the best explanation on delegates that i have seen

  • @samuelmartins1210
    @samuelmartins1210 2 года назад

    I have to say. I probably watched 10 or 15 tutorials about delegates and events in c#. This is by far the most effective and clear one. I think that most the coding RUclipsrs don't understand that when we want to learn something new, especially in programming where are so many layers of context, we want to learn in the simple way possible. And what I see most of the time, is the content creator explaining the thing that we want to learn attached to 20/30 other things that are not needed to explain this new thing that we want to learn. First, we ONLY want to learn the new tool, ONLY after that, we can try to apply that new tool to new contexts...So, Thank you for making a good example of what a tutorial must be. Congrats

  • @pafkataldr123
    @pafkataldr123 3 года назад

    Your two videos for Delegates and Events are the absolute best explanation in the internet. Thank you for this.

  • @BB-fv7ib
    @BB-fv7ib 4 года назад

    THANKS GOD other tutorials are like 30 mins boring and complex examples, but this one is amazing!!! Thank you so much!!!!!!!!!!!

  • @WaahaidIWKY
    @WaahaidIWKY 2 года назад +1

    THIS IS THE BEST VIDEO ON YT I HAVE EVER SEEN EXPLINING DELEGATES, Thank you learning this part was relly frustrating

  • @videolosss
    @videolosss 2 года назад

    Wow. Some people are gifted at taking troublesome topics and explaining them such that they seem simple. Thank you and very well done.

  • @Jose-uw3rj
    @Jose-uw3rj 8 лет назад +1

    Thank you very much, I've been programming for almost 3 years now but I never understood delegates. You explained it so clear that finally i learned what delegates are :D

  • @dalilapramenkovic8597
    @dalilapramenkovic8597 Год назад

    I really liked the examples. Straightforward, excellent explanation. Thank you.

  • @randall.chamberlain
    @randall.chamberlain 2 года назад

    Very down to earth explanation, wish I had seen something like this back in my freshman days.
    Delegates are a way to parameterize behaviour instead of just values. The way you used it here is perfect example of a functor in real life. C# was a pioneer in implementing these kind of patterns in the language by avoiding a plain old pointer while at the same time actually using one behind the scenes

  • @adamarzo559
    @adamarzo559 8 лет назад +1

    Awesome. A nice and clear way to explain why and how I should use delegates. Always wondered about them.

  • @cleoknight4788
    @cleoknight4788 3 года назад

    How the hell do I subscribe twice man I actually understand delegates now after scouring the entire internet for a half decent explanation

  • @mustafaozturk3343
    @mustafaozturk3343 6 лет назад

    This is one of the best delegate tutorial i have ever seen. Please keep more detailed tutorials about programmming. You ara awasome and thank you!

  • @vincentbaguette5366
    @vincentbaguette5366 5 лет назад

    I've been finding C# tutorial about delegates for so long
    Thx God, I found yours.
    After watching this, Delegates seems very easy.

  • @XnecromungerX
    @XnecromungerX 6 лет назад

    jesus christ. so many years of not knowing this. thankyou Sebastian

  • @ghostphalanx
    @ghostphalanx 6 лет назад

    Your videos are extremely professional and clean. The only problem I have is that you are so concise about what you say, that if I blink for a second a miss an important bit of information. Maybe you could take it just a tad slower. My brain would be very thankful. Great channel, already subscribed!

  • @tmkaplan94
    @tmkaplan94 2 года назад

    Best Delegate video I’ve seen. Nice job.

  • @TheFlyguy31
    @TheFlyguy31 7 лет назад

    Your tutorial put everything together for me and everything just 'clicked' cheers..Thank you, Sebastian much appreciated!

  • @ZionistHunter99
    @ZionistHunter99 8 лет назад

    I really liked this format for explaining concepts in C#. Top quality stuff

  • @nomadcrossfire
    @nomadcrossfire 8 лет назад +7

    where was this 2 semesters ago, nicely done as always

  • @RNGoD
    @RNGoD 5 лет назад +1

    Thank you, i've watched a lot of videos but this is the one that got to me. Simple how it works and why should you use it . Thank you .

  • @monsume123
    @monsume123 3 года назад

    Beautiful, thanks for taking the time to make this great video

  • @wildKawa
    @wildKawa 3 года назад

    Thank you so much for this video!
    I never thought about using delegates like that to be honest, i used to just use them in the most basic way to call multiple functions at once, always simply thought of them as event broadcasters. This combined with the lambda expression is going to make some of my code a lot cleaner and less boiler platey, thanks again! :3

  • @juliobrett-hall9437
    @juliobrett-hall9437 8 лет назад

    Thank you Sebastian! Another excellent tutorial. Looking forward to the part two. And really looking forward to a bigger more in depth tutorial on lambda expressions!

  • @dreamingacacia
    @dreamingacacia 4 года назад +2

    This is the third time I watched the video and I still couldn't follow, I'll watch several more times but I think I should read more document about it before pushing this thing into my head. I just have to learn this because it's needed for my game, it make life easier this way too.

    • @CustardCream33
      @CustardCream33 4 года назад +1

      Exactly how I feel! It is a good example but just isn't clicking.

  • @codegate615
    @codegate615 2 года назад

    this man knows how to explain

  • @josipstavalj1912
    @josipstavalj1912 4 года назад

    Definitely the best explanation of delegates i ever seen

  • @Kleineswiss19
    @Kleineswiss19 3 года назад

    clean and simple... bravo!!! Thank you very much!

  • @JonathanZigler
    @JonathanZigler 8 лет назад

    It's pretty cool, Lambda expressions are useful ,but variable initialization should be considered when passing functions because not only do you have to worry what's being put on the stack ,but the reinitialized variables can cause latency issues unless dealt with properly. Of course the instance you showed was perfectly fine because that isn't repeating unnecessary code . Good Job Sebastian!! I have high hopes for this mini-series!!

  • @ZeroSleap
    @ZeroSleap Год назад

    Huh! This a very interesting different way to approach this,you are essentially doing Parameter injection on the function. Giving it the implementation of scoreCalculator you really want when calling it.

  • @TESkyrimizer
    @TESkyrimizer 4 года назад

    I love this video so much. This channel is a real gem.

  • @eyalbiton5654
    @eyalbiton5654 4 года назад

    You are my hero, love your heap explanation from another video

  • @CalebHansonlets
    @CalebHansonlets 5 лет назад

    First time I've ever fully grasped lambda expressions

  • @ChibisOnTheLoose
    @ChibisOnTheLoose 8 лет назад

    That's very helpful!
    I had some trouble comprehending some of these concepts, but that clears things a lot.

  • @theGreaterAwareness
    @theGreaterAwareness 7 лет назад

    Wow, your tutorials are excellent learning tools. Thankyou for making these videos.

  • @AnsityHD
    @AnsityHD 8 лет назад +19

    Thanks for sharing, had no idea you could do something like this. Might take a while to get my head around before I start using it naturally in practice but it seems helpful :)
    Also you might want to name this episode Delegates, then the next episode Events. Like having it as 2 separate episodes rather than a short series? Just an idea :) Cheers.

    • @SebastianLague
      @SebastianLague  8 лет назад +7

      Hi, glad you found it helpful!
      I chose to make this a 2-part series because it makes a lot of sense to learn about delegates and events at the same time (given that events are simply delegates with a few restrictions). I've edited the title to clarify that this episode only covers delegates though. Cheers :)

    • @AnsityHD
      @AnsityHD 8 лет назад

      Sebastian Lague ah right that makes sense then, I had no idea what an Event was so I just imagined it was something completely different :)

  • @EdgePR0
    @EdgePR0 3 года назад

    OH MY GOD! I understood delegates in under 7 minutes!

  • @dreamingacacia
    @dreamingacacia 4 года назад

    Remember me ? Good news! I successfully understand this thing and E02: events. About a week huh ? Well at least it's paid off :D

  • @yannickfrogel3537
    @yannickfrogel3537 2 года назад

    Excellent Tutorial

  • @stevekingu1760
    @stevekingu1760 4 года назад

    Be blessed man.

  • @user-lt5zz8gv3q
    @user-lt5zz8gv3q 2 года назад

    thank you so much! noob as i can learn a lot from this.

  • @exewingaming
    @exewingaming 3 года назад

    Really good example, my code finally works!

  • @TheTrueLukeJester
    @TheTrueLukeJester 3 года назад

    Thank you so much!!! I finally get it!

  • @TheMarrt
    @TheMarrt 8 лет назад +1

    I'm always a bit confused about the differences between Lambda expressions, delegates and events (the things of the type "Action")
    But still I use Events for my Attack class. Each Attack has an impact-, hit- and activation-Event that is called within Invoke() of the Attack class. When the attack impacts on anything, hits a mortal-target or is activated it publishes the corresponding event with parameters like impactPoint, caster, hitObject etc... . The gain in this is that when i define an attack, i can put whatever function i like into those events or nothing at all. Therefore my utility-attacks use the same class and therefore Invoke as my spell-attacks, the only difference is that when i create the utility-attack i supply an activation effect only (e.g. instantiate some arbitrary game object like a lava patch) while on a normal attack i might define only a hit or impact effect.
    Without that i would have to create a new function for every single effect my spells might exert. I would have to have a specific function that creates a lava-patch within the Attack class but now i just write "spellLavaPatch.impactEffect (dir, caster, pos) => { CreateSpellObjectbyPrefab(lavaPatch, pos); }" when i define the attack and the creation is neatly included when i call "spellLavaPatch.Invoke(dir, caster);" anywhere
    At least that's what i do as of now, for me it is the first time utilizing those things.

  • @Jojo270573
    @Jojo270573 4 года назад

    Really good. Thanks

  • @ssojyeti2
    @ssojyeti2 3 года назад

    Amazing tutorial. I want to go over some of my old code and rewrite it now

  • @JoeisProductions
    @JoeisProductions 8 лет назад

    Awesome, can't wait for the next one!
    I would love to see some tutorials on Editor Scrips in the future. Keep it up!

  • @SwapnilSuryawanshis
    @SwapnilSuryawanshis 2 года назад

    Nice explanation.

  • @AmpDecay
    @AmpDecay 8 лет назад

    Great video and a good refresher from some stuff I learned in school. Keep it up.

  • @mounirdev9560
    @mounirdev9560 4 года назад

    You're the best, keep posting please!

  • @asembus
    @asembus 5 лет назад

    finally excellent use case for delegate usage

  • @HaydenTheEeeeeeeeevilEukaryote
    @HaydenTheEeeeeeeeevilEukaryote 7 лет назад +3

    Where did the "stats" come from?

  • @ez8719
    @ez8719 5 лет назад

    Thank you for the help! This was very great and is going to help me pass my c# test!

  • @muammarkaddafi3572
    @muammarkaddafi3572 7 лет назад

    Delegates is implemention of Delphi 'function of object' (well, it's Anders Hejlsberg after all...). It's kinda logical as using of pointers was declared 'unsafe' but programmers still need to get an access to methods.

  • @user-jp1mf3iy4m
    @user-jp1mf3iy4m 4 года назад

    Thanks, dude.

  • @vinzanity68
    @vinzanity68 4 года назад

    Best explanation for delegates...and yet I stil need time to digest this :D

  • @BirdyC
    @BirdyC 4 года назад

    Really good stuff, as always

  • @MrPicklerwoof
    @MrPicklerwoof 5 лет назад

    Events are great, but in some cases standard method calling can be more suitable - especially if you're making a strictly turnbased tactical game with an AI Sequence for example. I personally found that being able to see the methods being explicitly called within a complex algorithm (spread over several scripts) made it far, far easier to debug and analyse. I could pinpoint where I was going wrong much more quickly.
    Events are a no-brainer in free-flowing games though, where you have multiple instances of objects interacting with other objects on the fly (in a simple way). But it's worth knowing that it can obscure your code somewhat on bigger projects.
    Pretty much everything in Unity/C# has it's strengths and weaknesses, and events are no different.

  • @TheMasterpikaReturn
    @TheMasterpikaReturn 8 лет назад

    i gotta say, delegates are probably the most useful thing there is in c#. Being a javascript guy, i always hate to take the procedural approach in problems where map, filter, reduce and higher order functions can be used. But i have to say, the type safety introduces a lot of verbosity D:

  • @andresdurango6519
    @andresdurango6519 8 лет назад

    thanks for these videos man! Very helpful.

  • @MrBrown78
    @MrBrown78 8 лет назад

    Never knew about these thanks for the lesson!

  • @theblackdragon7321
    @theblackdragon7321 7 лет назад +1

    I am new to all of this, so do delegates optimize the code making it less redundant?

  • @duckman6403
    @duckman6403 4 года назад +1

    I don't understand this video that well, how do ScoreByKillCount and ScoreByFlagCaptures know about the delegate?

  • @nicoponxe
    @nicoponxe 3 года назад +1

    Excelent video!. My question is: why would I use a delegate instead of calling the function 'GetPlayerNameTopScore' twice with different arguments?

  • @steveklotz8896
    @steveklotz8896 8 лет назад

    Thanks, you made my life easier again :D

  • @Adoblem
    @Adoblem 6 лет назад

    thank you sebastian

  • @SMatin303
    @SMatin303 4 года назад

    Codes are become more and more intriguing as if some extraterrestrial are developing ✍️

  • @in801fo5
    @in801fo5 2 года назад

    I believe I have encountered a problem with delegates. They only work if there is only ONE instance of the object. The other ones will do what the first instace does.

  • @DarkLogic911
    @DarkLogic911 8 лет назад

    nicely explained!

  • @APlethora
    @APlethora 8 лет назад

    Great video!

  • @marularch
    @marularch Год назад +1

    I just don't understand the part where he passes in scoreCalculator at 5:30, can someone please explain? There is no function that's defined, so what's happening?

    • @theblackdragon7321
      @theblackdragon7321 Год назад

      I know this is 4 months old, but scoreCalculator is just the name for the delegate and an integer is what gets passed in because at the top of the code is the delegate with the integer type. Hope I explained this well enough for you

  • @furkanturkal8414
    @furkanturkal8414 8 лет назад

    Thanks for english sub-title. :)

  • @luislodosm
    @luislodosm 5 лет назад

    Beautiful.

  • @Kwuasimoto
    @Kwuasimoto Год назад

    Would it make sense to compare delegates in C# too callback functions in JS/TS? Are there any important discrepancies between the two?

  • @bananenbroek4
    @bananenbroek4 8 лет назад

    You might want to rename this episode to *just* delegates, since that is the only thing that you covered in this episode :P

  • @tymewiz806
    @tymewiz806 8 лет назад

    the way i see it is that the only two uses for delegates are to make the input or output of a function be itself a function,(an example of which is shown in this video), and using them as events.
    Is there an example of a situation where it would be appropriate to call an event instead of calling all the functions i know to be listening to the event directly?

  • @Hydra-tm7qm
    @Hydra-tm7qm 4 года назад

    cool, make me understand delegate deeper

  • @Rahulsingh-theraha
    @Rahulsingh-theraha Год назад

    sounds very similar to passing the reference of a function

  • @twinspectre
    @twinspectre 3 года назад

    Sorry, but can You explain in depht what it is "stored" inside the myDelegate(50) at timestamp 02:36 line 11?

  • @iamgingerbread6558
    @iamgingerbread6558 11 месяцев назад

    what is the color pattern you are using for you code in this video, i really like it!

  • @AbhimanyuAryan
    @AbhimanyuAryan 7 лет назад

    do more stuff like this....Thanks :)

  • @Hozgen
    @Hozgen Год назад

    actually we can assume than a delegate is a kind of class or in use of class at the same time

  • @iliyavalchev7757
    @iliyavalchev7757 6 лет назад

    Amazing! Thanks :)

  • @bissash103
    @bissash103 6 лет назад

    WoW! Grate video!

  • @Xeros08
    @Xeros08 5 лет назад

    What happend to lambdas? Cant see a video about them

  • @vijayxdd
    @vijayxdd 5 лет назад

    masterpiece

  • @awaisshafiq7129
    @awaisshafiq7129 4 года назад

    Hi. I would really appreciate a tutorial on how to do this in unity.

  • @boononmoon5164
    @boononmoon5164 8 лет назад

    Hi, nice tutorials as always. I was wondering if you actually have finished a complete game?

  • @StormtrooprDan
    @StormtrooprDan 6 лет назад

    Could you tell me the theme and font you use for your editor? It looks really nice.

  • @INeatFreak
    @INeatFreak 5 лет назад

    But steel is heavier then feathers? I don't get it.

  • @shirosurfer8864
    @shirosurfer8864 5 лет назад

    Suple, super thank you

  • @pencode
    @pencode 2 года назад

    So, in short, delegates are like variables for storing and invoking methods?
    Int x = "Hello world!" // Doesn't work
    delegate void DelegateTest();
    string StringReturnMethod(){
    return "Hello world!"
    }
    DelegateTest myDelgate = StringReturnMethod; // Also doesn't work
    Fascinating... ^^

  • @Daymianpac
    @Daymianpac 5 лет назад

    I'm having trouble understanding the foreach statement.. why is 'stats' allowed when it was not declared.?? is it because of the 2nd parameter scorecalculator??

    • @ferdowsurasif
      @ferdowsurasif 4 года назад

      @3:45 stats is being declared while in use