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

Поделиться
HTML-код
  • Опубликовано: 7 ноя 2024

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

  • @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.

  • @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)

  • @uzferry5524
    @uzferry5524 8 лет назад +175

    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.

    • @pixeldriftcollective
      @pixeldriftcollective 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.

  • @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

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

    Hello, I hope you enjoy this mini-series on delegates and events. The second part should be out in a day or two.
    If you'd like to translate this video, you can do so here: ruclips.net/user/timedtext_video?ref=share&v=G5R4C8BLEOc

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

      Dude, its awesome. I wish I saw this video like few years ago, when I was trying to figure out what the hell it is, all those delegates and lamba expressions :D
      This video is extremely helpful and easy to understand (imo)

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

      I already learned about those before... But I never actually used them so now at least I will have reference to this whenever I forget something about events, as this is my favourite Unity tutorial channel so far.
      EDIT: that scoring example was literally best I've ever seen.

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

      Isn't it FUBAR?

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

      Not in programming :)
      en.wikipedia.org/wiki/Foobar

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

      I made a spanish translation for your video :D

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

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

  • @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!!!

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

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

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

    It was the best explanation on delegates that i have seen

  • @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.

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

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

  • @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

  • @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

  • @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

  • @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 3 года назад +1

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

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

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

  • @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

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

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

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

    Definitely the best explanation of delegates i ever seen

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

    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!

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

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

  • @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!

  • @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 .

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

    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

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

    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

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

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

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

    Best Delegate video I’ve seen. Nice job.

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

    where was this 2 semesters ago, nicely done as always

  • @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.

  • @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.

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

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

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

    this man knows how to explain

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

    finally excellent use case for delegate usage

  • @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!!

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

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

  • @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?

  • @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.

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

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

  • @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.

  • @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

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

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

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

    You're the best, keep posting please!

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

    Excellent Tutorial

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

    Be blessed man.

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

    Where did the "stats" come from?

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

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

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

    First time I've ever fully grasped lambda expressions

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

    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.

  • @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 :)

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

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

  • @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:

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

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

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

    Really good example, my code finally works!

  • @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

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

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

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

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

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

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

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

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

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

    Nice explanation.

  • @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!

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

    Really good stuff, as always

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

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

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

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

  • @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

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

    Really good. Thanks

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

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

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

    thanks for these videos man! Very helpful.

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

    Never knew about these thanks for the lesson!

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

    thank you sebastian

  • @НикитаЗеленцов-б1й

    Thanks, dude.

  • @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?

  • @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... ^^

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

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

  • @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

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

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

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

    nicely explained!

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

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

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

    Great video!

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

    Thanks, you made my life easier again :D

  • @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.

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

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

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

    Thanks for english sub-title. :)

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

    Eu não sei quem foi mas um filho de Deus coloco a tradução pra pt br e não a do google tradutor que né ,obrigado cidadão.

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

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

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

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

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

    For what it is worth... it is actually F.U.B.A.R. (short for F'ed Up Beyond All Recognition)

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

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

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

    Do you have a time table for the Lambda episode? I'm having trouble understanding them myself, that or a link to a good explanation of them would be terrific. Thanks!

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

      RUclips has some good tutorials on that, anyway, he didn't make that video yet.

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

      I don't have any immediate plans for the lambda episode. You might find Jamie King's video on the topic helpful:
      ruclips.net/video/KRjeu9Thp3s/видео.html

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

    Beautiful.

  • @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

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

    What happend to lambdas? Cant see a video about them

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

    Is there a specific reason why you wouldn't use LinQ for this? Or did you just need an example for Delegates? Just interested, maybe LinQ is more expensive or something.
    string playerNameMostKills = allPlayerStats?.Max(i => i.kills)?.name ?? "Unknown";
    string playerNameMostFlagCaptured = allPlayerStats?.Max(i => i.flagsCaptured)?.name ?? "Unknown";

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

      No, it's just for the sake of the example.

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

      Fair enough! Keep up the great content!

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

      i'm gonna throw my two cents out there, but i don't know how safe it is to use linq in unity. LinQ is probably more expensive in a lot of cases, and some options don't work on some platforms, though it's most definitely not the case with the example given. One thing i have to ask, are the ? thrown in there the null-conditional operator?

  • @Rahulsingh-theraha
    @Rahulsingh-theraha 2 года назад

    sounds very similar to passing the reference of a function

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

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

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

    didn't explain the basis of it, just the method of it. He jumped to passing a delegate as a parameter without a by-your-leave as if it was everyday thing