I personally feel the universities themselves should pay you for making such quality content accessible to computer science students all over the world! God bless!
0:00 - Intro 1:19 - Demo application walk through (WinForms) 3:18 - Code behind the demo app 18:28 - Event: Button click 21:21 - Creating and Invoking custom Event 26:35 - Event " ?.Invoke() " explained 30:00 - Listening to and writing code for the Event 34:00 - Creating the custom Event: Event in action and recap 37:12 - Event argument information: debugging 38:42 - Creating Another custom Event (overdraft event) 43:28 - Listening for the event in multiple places 46:33 - Removing Event Listeners form memory 49:00 - EventHandler: Passing class for T 53:39 - why not to use "public set" for properties 59:25 - Exception when to use public set 1:06:13 - Summary
I've been coding for decades. WPF since about 2012. Always under pressure to get code delivered and make sure I don't break code I already have. I have rarely had time to become expertly proficient in most of the things I code and oh yeah.. xaml is my nemesis. I've got a few weeks of time before the next big project begins and I want to step up my game each time I start a new app as there won't be a lot of time for massive changes along the way. Corey's tutorials are so helpful for me to gather my wits and learn more before I begin again. Thanks Corey.
i dont mean to be so off topic but does anyone know of a method to get back into an instagram account..? I somehow lost my password. I would appreciate any assistance you can give me
Greatest teacher ever! I have listened you and i went on step 1 instead on going on step 3 or 4 as you said in your first video of Getting started with C# even if i knew something about C# but i was rusty. Everything is understandable and personally i receive knowledge very easy. PS: I am really glad that every few days you have 1k more subscribers, you really deserve it ! Every here and when i recommend you to my friends or people that are interested in programming. Keep up the good work, you are rare diamond on UA-cam. Best regards !
Great content man. I'm interviewing for a senior .NET developer position next week and am watching some of your content on things I haven't ran into in my daily work and your content is super helpful and informative. Good stuff dude. People like you change so many lives by helping them gain marketable skill sets in the real world.
Good luck with the interview! Please let us know how it goes. Check out Tim's Dev Questions videos about interviewing to help you get in the right frame of mind - ua-cam.com/users/IAmTimCoreysearch?query=interview
@@tomthelestaff-iamtimcorey7597 It turned out not to be a technical interview but rather a more conversational interview. I think spending hours by myself in the dark looking at code may have ended up being more of a detriment than anything else hahaha. It did go well though; waiting to hear back but it was very recently so here's hoping.
I just stopped by this video to refresh myself on some concepts with events. I don't comment on every video of yours because I'd be pretty much repeating myself every time but: I started learning to code last October. I settled on learning C# somewhat arbitrarily (originally I wanted to have a go at making video games in Unity), and quickly realised that programming was something I was passionate about. Thanks to you, in less than a year I have become confident in a whole host of topics, from building ASP.NET Core (Razor & MVC) web apps, carrying out data access, and unit testing my code; to designing applications with a clean decoupled architecture and a focus on separation of concerns. Not only that, I am now starting to be offered Software Development jobs (something I thought would be impossible without a Computer Science degree) and feel like not only do I have a decent knowledge of these topics but I know what to do and where to look to improve on that knowledge! So, yes, I just wanted to say many thanks for uploading these videos! I have subscribed to your mailing list - and I direct friends/anyone interested to your channel and website when they ask about C#. Absolutely stellar job - you have literally opened up a career for me and for that I am extremely grateful! I look forward to seeing what you continue to produce! - Matt
27:11 "There's no point of saying if something new happen, if no one cares" well that's one sentence I'll remember forever :) great as usual Tim, it's nice to refresh to my knowledge about C#, even if it's my everyday, used at work language. One video a day makes it easier to remember all these amazing features and their concepts.
Hi Tim, I've been a subscriber to your channel for a while now, but obviously only since after the publication of this video. I had reached a point in my current project where I felt I could probably achieve my target through exceptions, but couldn't work out how to do it. I looked at a load of text tutorials on-line, each more overly complicated than the last. Then I found your video here. It was super easy to follow, really clearly explained, and I managed to implement exceptions in my own project, alongside watching you explain it. Thank you very much :)
Thanks Tim. Best explanation of C# Events. I have checked Pluralsight, Linkedin Learning and several online content for C# events and this is by far the best explanation of how practically to use events.
Hi Tim, thank you very much for this, I watched the other videos on Events and now this one, and NOW I have a really good understanding how events work and how to reduce the linear flow of my applications through events. I really did not understand how this worked until now. Books or other youtube videos fall way short of the way you have designed and presented this demo application to show us how to use events in a real world application. Also, grateful for the source code that you supply with these videos so that we can learn by doing. I hear, I forget; I see, I remember; I do, I understand!
Tim Corey your videos are amazing I love the free content so much a bought a few of your courses during the black Friday sale. Thank you I have learned so much from your content!
Tim Corey, great job on explaining events and showing how to add custom events. I love C# and use it everyday. This video gave me some new info that will be very helpful!! Thanks.
Mr. Corey, your C# channel is perhaps my most favorite! By the way, will you ever make a video on the Bitmap class (because there are not sufficient videos on UA-cam covering image manipulation with C#)? Perhaps image manipulation is not a topic that is strictly relevant to the engineering side of things, but it's still useful for UI/UX!
A Question : You mentioned that when passing an object through the event; that the setters in the properties of that object need to be private to prevent every listener from modifying them. My question is; when passing the object, isn't it a copy of the object?(by value) and thus the changes on that object by the listeners shouldn't affect the original object? Maybe i missunderstod something. Thank you for your valuable knowledge!
Thank you! As for the object copying, objects are actually never copied. The variables hold a reference to the object so when we pass an object into a method (or event), we are passing the reference even though the parameter is "by value" by default.
Question about removing event listeners: you mentioned on a form’s Close event; can you also do it as part of the form’s destructor, since a form is a class?
As far as I've understood it and from my experience in other languages, events are mostly used in GUI contexts, like button clicks and similar. Would you say it is wrong or bad practice to use events for other purposes than GUI, more specifically for monitoring the data on the model side of an application? For example, my current practice project is a small game. I'm thinking that using events to listen to a character's health points can then invoke an event CharacterDiedEvent and modify other classes accordingly, for example. So I will use the event purely for the model and not for the view.
I love your way of teaching, it's very simple and practical, but in my opinion, you should put your video about event after delegate. Event and delegate are not only very closely related, under the hood delegate is the foundation for event and explaining event - again in my opinion only - without mentioning delegate first is harder and easier to get confuse
I understand. The reason I usually switch the order, though, is because people are used to events. Doing something when a button is clicked is usually one of the first things a developer learns (not my recommended order). So, wrapping your mind around events is easier than delegates. Once you know how events work, you can expand to delegates are easier to understand (which is a good thing since they are complicated).
@@IAmTimCorey thank you for your response. Wow that's kind of weird to learn event like that, because the first question that would pop up in my mind is: "what is that EventHandler thing" but I can see why event would come up so early for window app developer. Thank you again
Thanks a lot Tim. One question please, If the part we clean up the event listeners by -= the handlers is so standard, why didn’t Microsoft do for us? I mean like using statement. Thanks again.
Thank you Tim for making C# Events so easy to understand that C# beginner can understand. I had a confusion though: Am I right in saying that, removal of Events such as recordTransactionsButton_Click, errorMessage_Click is taken care of by Visual Studio but the events such as TransactionApprovedEvent, OverdraftEvent that we create must be removed by us. Also, where in the code should I put customer.CheckingAccount.OverdraftEvent -= CheckingAccount_OverdraftEvent; to remove CheckingAccount_OverdraftEvent?
Hi Tim, May I ask why we need to use IReadOnlyList for Transactions? This property (Transactions) do not have set for outside of class to change the value.
To prevent another programmer in the bank accidentally/intentionally modifying a list that comes from that class. It is not powerful protection by itself (because you can make anew list with the same contents) against error/fraud but once you combine it with the full suite of fraud/error controls at the bank it becomes more useful.
@@michaelnurse9089 Ok yours makes sense but makeing a property type just IList ( instead of IReadOnlyList) and returning _transactions.AsReadOnly () in getter will not be sufficient protection. I mean if we return _transaction.AsReadOnly() in getter, why we should use IReadOnlyList type rather than just regular IList ???
IAmTimCorey Even though the other tutorials were in Russian) Imagine how good this tutorial has to be if English is my 3’rd language))) Imagine how bad is my English but still i had no problems with understanding how events work)
Hey Tim, Great video again. I've always had trouble wrapping my head around the whole 'events' thing. In the past I've read some pretty compicated stuff, but that was all explained from the point, which is still true of course, that it all starts at the point where you get to learn about delegates, after which it gets increasingly complicated. For me, that is. But your video made it much clearer. Just to be shure I'm doing the unsubscribing of the events the proper way, this is the code I devised for that purpose: private void Transactions_FormClosing(object sender, FormClosingEventArgs e) { _customer.CheckingAccount.OverdraftEvent -= CheckingAccount_OverdraftEvent; } I had to go for the _customer, since customer is a function parameter of the constructor and therefore not accessible outside of that. private void Dashboard_FormClosing(object sender, FormClosingEventArgs e) { customer.CheckingAccount.TransactionApprovedEvent -= CheckingAccount_TransactionApprovedEvent; customer.SavingsAccount.TransactionApprovedEvent -= SavingsAccount_TransactionApprovedEvent; customer.CheckingAccount.OverdraftEvent -= CheckingAccount_OverdraftEvent; } Or is it better to do this inside the _FormClosed event? BTW, is there a way to check if there are memory leaks should one omit this sort of code? Thanks, Peter
The FormClosing event is the place to do it. You don't really need to do it in your main form, since when that form closes the application closes but that all looks right. As for checking for memory leaks, I'll be doing a video on that in the future. You can use a profiler to track your usage.
That way exposes the EventHandler as a public field, which would allow it to be overwritten instead of just subscribed to. It is considered a dangerous practice: stackoverflow.com/a/46824847/733798 Good question.
Hi Cory, Really enjoyed your vids and have learned alot. I have used c before but now I am looking into the interface to my windows laptop. At the present time I program my own devices and enjoy learning programing. I only write my own files at this time. for my stuff. Thanks again, Len
Hello Tim, I started watching your videos recently and they have been very good. I went to your patreon page and was looking through the Tiers. I think you have a small typo on the first Tier for $1: " Did you know paying just $1/month provides me with more income than UA-cam ads do for all of your views? So if you are wondering if this matters, is absolutely does. " I assume the last three words of that string are supposed to be "it absolutely does" instead of "is absolutely does". Just thought you would like to know. Thanks for the videos!
The communication between the two Forms and the customer class can also be done by adding bindings to the Form controls. Would you prefer to use data binding or to set up events? Thanks, Tim!
very informative and helpful. in the start to finish course, you always used the wiredup() method, does that means we can call an event there as well or eventhandler will not work there. thanks for all the good work that you put in your videos and they really are helpful.
Nice to know about events. I guess we can use it whether windows form or wpf but i dont feel comfortable with windows forms. Drag and drop feels just not corret. Anyways, everything will be more clear on user interface section :))
I started on WinForms and doubting what to do next. I understand the feeling of it not being correct, but the WinForms designer is so easy to use for starters..
Awesome stuff! I have a question, how could you trigger and event in the background when for example gamepad controller was connected or disconnected? I do not know where to handle the event listener that it would check if the controller is connected or not! thanks in advance! BR
at 54:03, what if we just write "public event EventHandler OverdraftEvent;" without the ""? when we invoke the event and pass an instance of OverdraftEventArgs, it appears to work fine. Is there an advantage of being specific about ?
Hey Tim... Just had a little query... I still don't have any idea of WPF and even Winforms... So could you please tell me how I could practice the events? I admit that it's possible to practice with the demo, but I want to apply it once myself....
I can't specifically answer that questions, but I can point you to Tim 'Intro to WPF' - ua-cam.com/video/gSfMNjWNoX0/v-deo.html Please consider checking it out!
You can create console applications and try things out. Events work fine in console. Make them trigger when something is near full - like a list or a game level is almost complete or something like that.
So, I know this is a month late, but I'll try my best to explain how you could consolidate this code. Both Account Event functions do very similar logic with very similar data types. Each resets and fills it's list boxes, and change a Text Element's value. What we could do is write another function called something like UpdateFormWithNewTransactionInfo with parameters of (ListBox box, Label label, Account account). Then we'll just put in generic code and pass in the data we actually want to change as parameters. Think something like this: private void UpdateFormWithNewTransactionInfo(ListBox box, Label label, Account account) { box.DataSource = null; box.DataSource = account.Transactions; label.Text = string.Format("{0:C2"}, account.Balance); }
Hi Tim! I highly appreciate you for providing us such a valuable content. I have a question about Events. For me it looks that everything you done by implementing events in this movie, may be achieved by implementing just appropiate plain functions. Is it true? Anyway, why really we should use events? I understand how they works, but i'm sure that i wouldn't be able to decide when use events, and when not in my code.
Events allow you to act in a disconnected manner. Yes, you could just create a function but then the event caller would need to know about a method on the event receiver. That creates a tight coupling. Think about Windows Forms. When you click a button, you want something to happen, right? If that button click didn't fire an event but it called a method, how would you add your code later? Microsoft created the button. They would have to know which method(s) to call when they build the button but your methods weren't created until years later.
Hi Tim! In the real world MVC app how would you go about associating two Accounts with the Customer class? In your demo you are using Checking and Savings accounts as properties of Account type. Would you have ICollection in Customer class in MVC or two classes one is for Checking and one for Savings and then use navigation properties to each one of them?
Because that public get would get you a reference of the list and you can alter that list in any way you want including adding and removing items. The private set only prevents you from exchanging the list reference in the property. A ReadOnlyList on the other hand makes the elements IN the list readonly as well, so you can get an element at an index but not set.
Hello Tim! In this case, which one is the Publisher and which one is the Subscriber? Is the publisher in the UI or is it the one with the .Invoke() method? And the subscriber is the one which is called with the Invoke() method?
Hi Tim! I have a question about the first event - TransactionsApprovedEvent. Can I replace this event with a Binding Source? I mean I could declare a new Binding Source and assign it to our transactions list from Account Class. Will it work? Of course, I would like thank you for this video. Your way of explaining C# is always awesome :)
Hi Tim, I have 2 questions 1. To understand events, do I need to understand delegates as events use delegates? 2. To understand Routed events, is it necessary to understand normal events. And can you pls tell me why do we need routed events in WPF as we can use normal events to fire up something like Button click in WPF?
You don't have to understand delegates to understand events. I actually figured out events before I ever understood delegates. However, once you understand delegates, you will better understand events. Routed events allow you to fire the event in more places than just the caller. Personally, I wouldn't stress over one vs. the other. Here is an explanation that might help: www.wpftutorial.net/RoutedEvents.html
I was wondering if you had any videos or recommendations to learn Add/Remove properties for multiple events. I saw it on the Microsoft website but I'm not sure of its utility nor when to use it. The whole thing with EventList and creating static read only objects
@@IAmTimCorey Awesome! I'd be waiting. I was also wondering if you had like a discord channel for folks who watch your videos to interact and share projects and progress
A litte before 32:24 when you tabbed for ApproveCustomerTransactionEvent, a function was created but on the line that you were typing there was no parenthesis. Was that a reference?
It is different (but similar looking, I agree). This checks to see if the item is null. If it is null, it stops there. If it is not null, it allows the property to be checked.
Cool, I have a question, what's the difference between event and Action? I've used the later for a Unity project but I wonder if there's a difference between the two (knowing that Unity doesn't use the latest .NET framework and that the example I had seen used two lines for the event/delegate).
Actions are delegates. Events use delegates. There is a distinction between delegates and events but it is small. I'm going to be doing a video on delegates soon, so you will more clearly see the differences and uses there.
Tim I know you are a huge fan of using Windows when building your apps. Since the release by Microsoft dotnet core for all 3 platforms now with a little work you can not only build and run your apps within either OSX or Linux. Then on that subject build an app using the built in API with Angular. Do you have any further plans for this?
I'm currently working on a full application course where the application is built fully in .NET Core (a web-based helpdesk system). I'll be building on Windows because that is what I have but I'll surely accept the donation of a new MacBook to do videos on :-) Just note that while .NET Core runs on any platform, WinForms, WPF, and UWP do not so they can only be built in Windows and run on Windows. .NET Core 3.0 is bringing .NET Core to WinForms and WPF but they still won't run on anything but Windows (and you can't build them on anything but Windows as well). There is a benefit to making them .NET Core but it isn't about cross-platform.
I've watched this twice now as I am blown away how easy it appears to be to update the UI as a result of a method running in a separate class. How does this compare to BeginInvoke for threadsafe UI updates? Is it suitable to have several event handlers running for UI update from classes- for a small app I'm guessing it's not too resource hungry. For example- if I had a Db checking class which ran on a timer to check for data changes every second - would an event handler be the best way forward. I am coming from a almost complete beginner position and someone who has struggled with UI updates from classes and thread safety. Big love for all your videos - really learning a lot!
Events aren't really memory-hungry. There is nothing active really. They are just stored methods that get fired when they are called. An event that gets fired when an update to the database is discovered would definitely be a possible solution for your situation.
That's great thanks Tim. I've also found out how important the ? Is when invoking the event. Form1 had stopped listening and it was throwing a null exception. Had I not known about that little gem I would still be screaming at my code. Really good videos - keep up the good work.
as of till 43:00 , can you do the same thing witout these events ( i mean the ones created by us ). Like for the error shown, cant we just do it with a normal function?
Everything that can be done with events can also be done with functions. It's much less overhead, far safer and much, much easier to debug. There are exceptions like in banking where a continuous transaction record is needed, but then... if you are in one of the fields where this is necessary, this video is not the one who will teach you how it's done correctly. Your supervisors at your workplace will make sure that you are up to date on the best practices of the industry.
@@IAmTimCorey thank you sir but i would rather that you consider making a video about this topic because you know how to explain things and make it easy to understand fankly i read a ton of articles but i couldn't get what i need especially the best practice when it comes to this problem
Thank you Mr. Tim and I have question ?! can I use event in database object on property change value make auto update something updated directly to database
@@IAmTimCorey Thank you for answering my question. Can you make example with three tires application dal, bi and ui With genral repository and unit of work Thank you
Thanks a lot for uploading this video . I was struggling to understand how events work underhood before watching this video . Where do we write the code for cancelling the events ? Is it in finally block or as well as exceptions
I assume you mean cancelling the event going forward (so if this is the first method called, the others don't get called). That can be tricky since you don't know what order you are in necessarily (are you first, are you last, or are you in the middle somewhere). The actual call to cancel the event can be anywhere you want it to be. However, I don't think you will get much benefit from doing so. Cancelling a keyboard event (keypress) is a thing because you know your event is fired before the key is processed. Therefore, cancelling the event cancels the standard key press action. In almost every other case, cancel just makes your application less predictable. Remember that the event that triggered the event calls already happened. You aren't cancelling that action. Just the rest of the responses to it.
Tim, one of my friends was asked a question in interview like whats advantages of events over delegates? Isn't it wrong question to ask this. Events use delegates to work. But how can we compare them?
There is little difference between events and delegates. Events add a bit of protection on the top of delegates and they serve a bit different purpose (alerting a listener vs using code from somewhere else). For most purposes beyond minor quibbles, there isn't really a difference.
I personally feel the universities themselves should pay you for making such quality content accessible to computer science students all over the world! God bless!
Thank you for the kind words.
He is literally the best teacher for computer science ever. I mean he still replies to my comments. He is the first person i donated some money too.
0:00 - Intro
1:19 - Demo application walk through (WinForms)
3:18 - Code behind the demo app
18:28 - Event: Button click
21:21 - Creating and Invoking custom Event
26:35 - Event " ?.Invoke() " explained
30:00 - Listening to and writing code for the Event
34:00 - Creating the custom Event: Event in action and recap
37:12 - Event argument information: debugging
38:42 - Creating Another custom Event (overdraft event)
43:28 - Listening for the event in multiple places
46:33 - Removing Event Listeners form memory
49:00 - EventHandler: Passing class for T
53:39 - why not to use "public set" for properties
59:25 - Exception when to use public set
1:06:13 - Summary
Thanks! I added it to the description.
I've been coding for decades. WPF since about 2012. Always under pressure to get code delivered and make sure I don't break code I already have. I have rarely had time to become expertly proficient in most of the things I code and oh yeah.. xaml is my nemesis. I've got a few weeks of time before the next big project begins and I want to step up my game each time I start a new app as there won't be a lot of time for massive changes along the way. Corey's tutorials are so helpful for me to gather my wits and learn more before I begin again. Thanks Corey.
Excellent!
i dont mean to be so off topic but does anyone know of a method to get back into an instagram account..?
I somehow lost my password. I would appreciate any assistance you can give me
WHen i found ur channel i felt like i've won in lottery. Such nice and clear explanations, really love it, thank u very very much, Tim. U r doing nice
I am glad you found it so helpful.
Greatest teacher ever! I have listened you and i went on step 1 instead on going on step 3 or 4 as you said in your first video of Getting started with C# even if i knew something about C# but i was rusty. Everything is understandable and personally i receive knowledge very easy.
PS: I am really glad that every few days you have 1k more subscribers, you really deserve it ! Every here and when i recommend you to my friends or people that are interested in programming. Keep up the good work, you are rare diamond on UA-cam. Best regards !
I am glad it has been helpful. Thanks for recommending the channel.
Hi, Tim. You are the best C# instructor.
I appreciate the kind words.
For sure he is ❤️❤️
Great content man. I'm interviewing for a senior .NET developer position next week and am watching some of your content on things I haven't ran into in my daily work and your content is super helpful and informative. Good stuff dude. People like you change so many lives by helping them gain marketable skill sets in the real world.
Good luck with the interview! Please let us know how it goes. Check out Tim's Dev Questions videos about interviewing to help you get in the right frame of mind - ua-cam.com/users/IAmTimCoreysearch?query=interview
@@tomthelestaff-iamtimcorey7597 It turned out not to be a technical interview but rather a more conversational interview.
I think spending hours by myself in the dark looking at code may have ended up being more of a detriment than anything else hahaha.
It did go well though; waiting to hear back but it was very recently so here's hoping.
@@bleepbloop6303 Thanks for the update. Let us know!
I just stopped by this video to refresh myself on some concepts with events. I don't comment on every video of yours because I'd be pretty much repeating myself every time but: I started learning to code last October. I settled on learning C# somewhat arbitrarily (originally I wanted to have a go at making video games in Unity), and quickly realised that programming was something I was passionate about.
Thanks to you, in less than a year I have become confident in a whole host of topics, from building ASP.NET Core (Razor & MVC) web apps, carrying out data access, and unit testing my code; to designing applications with a clean decoupled architecture and a focus on separation of concerns. Not only that, I am now starting to be offered Software Development jobs (something I thought would be impossible without a Computer Science degree) and feel like not only do I have a decent knowledge of these topics but I know what to do and where to look to improve on that knowledge!
So, yes, I just wanted to say many thanks for uploading these videos! I have subscribed to your mailing list - and I direct friends/anyone interested to your channel and website when they ask about C#. Absolutely stellar job - you have literally opened up a career for me and for that I am extremely grateful! I look forward to seeing what you continue to produce! - Matt
This is why I am passionate about my work. I love hearing these stories. Thank you for sharing your journey!
Good job keeping it DRY! Ha, sorry, couldn't help myself :)
27:11 "There's no point of saying if something new happen, if no one cares" well that's one sentence I'll remember forever :) great as usual Tim, it's nice to refresh to my knowledge about C#, even if it's my everyday, used at work language. One video a day makes it easier to remember all these amazing features and their concepts.
I'm glad it made an impression.
Great teaching. For others who think Tim's videos r long, who come here to pick quick things, no this is organic teaching, not junk food learning.
Thank you!
There's a middleground. 17 minutes in and this guy still hasn't said anything.
Hi Tim, I've been a subscriber to your channel for a while now, but obviously only since after the publication of this video. I had reached a point in my current project where I felt I could probably achieve my target through exceptions, but couldn't work out how to do it. I looked at a load of text tutorials on-line, each more overly complicated than the last. Then I found your video here. It was super easy to follow, really clearly explained, and I managed to implement exceptions in my own project, alongside watching you explain it. Thank you very much :)
Awesome! I'm glad it was so helpful.
Thanks Tim. Best explanation of C# Events. I have checked Pluralsight, Linkedin Learning and several online content for C# events and this is by far the best explanation of how practically to use events.
Thanks! I appreciate the kind words.
You're such a good teacher. Just wanted to let you know. Keep it up
I appreciate that!
I take it slow and spend my two day for events. Now i understand whole thing. Perfect.
Great!
Hi Tim, thank you very much for this, I watched the other videos on Events and now this one, and NOW I have a really good understanding how events work and how to reduce the linear flow of my applications through events. I really did not understand how this worked until now. Books or other youtube videos fall way short of the way you have designed and presented this demo application to show us how to use events in a real world application. Also, grateful for the source code that you supply with these videos so that we can learn by doing. I hear, I forget; I see, I remember; I do, I understand!
I am glad it was helpful.
Thank you very much for an explanation of the very details of this pretty complicated concept Mr. Corey!
You are welcome.
Tim Corey your videos are amazing I love the free content so much a bought a few of your courses during the black Friday sale. Thank you I have learned so much from your content!
Awesome! I'm glad have learned a lot from my content.
This video is really incredible, as always. Thank you Tim.
Tim Corey, great job on explaining events and showing how to add custom events. I love C# and use it everyday. This video gave me some new info that will be very helpful!! Thanks.
Glad it was helpful!
Dear Tim, once again, thank you very much.
You are welcome.
Quality! beautiful teaching
Thank you!
Thank you so much. I was struggling to make custom Events for so long. But with this VERY clear explanation , I can finally do it easily.
Glad it helped!
Thanks!
Thank you!
Mr. Corey, your C# channel is perhaps my most favorite! By the way, will you ever make a video on the Bitmap class (because there are not sufficient videos on UA-cam covering image manipulation with C#)? Perhaps image manipulation is not a topic that is strictly relevant to the engineering side of things, but it's still useful for UI/UX!
I will add it to the list. Thanks for the suggestion.
Thanks
A Question :
You mentioned that when passing an object through the event; that the setters in the properties of that object need to be private to prevent every listener from modifying them. My question is; when passing the object, isn't it a copy of the object?(by value) and thus the changes on that object by the listeners shouldn't affect the original object? Maybe i missunderstod something. Thank you for your valuable knowledge!
Thank you! As for the object copying, objects are actually never copied. The variables hold a reference to the object so when we pass an object into a method (or event), we are passing the reference even though the parameter is "by value" by default.
Very helpful course with nice n clear explanation. Many thanks Tim.
Very welcome
Question about removing event listeners: you mentioned on a form’s Close event; can you also do it as part of the form’s destructor, since a form is a class?
As far as I've understood it and from my experience in other languages, events are mostly used in GUI contexts, like button clicks and similar. Would you say it is wrong or bad practice to use events for other purposes than GUI, more specifically for monitoring the data on the model side of an application?
For example, my current practice project is a small game. I'm thinking that using events to listen to a character's health points can then invoke an event CharacterDiedEvent and modify other classes accordingly, for example. So I will use the event purely for the model and not for the view.
If match your requirements, why not?
No, it isn't bad practice. Events are used for a lot more than just GUIs.
Event driven programming is used as a design practice for decoupling, publish/subscribe design pattern...from what I've read.
I love your way of teaching, it's very simple and practical, but in my opinion, you should put your video about event after delegate.
Event and delegate are not only very closely related, under the hood delegate is the foundation for event and explaining event - again in my opinion only - without mentioning delegate first is harder and easier to get confuse
I understand. The reason I usually switch the order, though, is because people are used to events. Doing something when a button is clicked is usually one of the first things a developer learns (not my recommended order). So, wrapping your mind around events is easier than delegates. Once you know how events work, you can expand to delegates are easier to understand (which is a good thing since they are complicated).
@@IAmTimCorey thank you for your response. Wow that's kind of weird to learn event like that, because the first question that would pop up in my mind is: "what is that EventHandler thing" but I can see why event would come up so early for window app developer. Thank you again
I'm actually falling in love with this stuff
Excellent!
Thanks a lot Tim. One question please, If the part we clean up the event listeners by -= the handlers is so standard, why didn’t Microsoft do for us? I mean like using statement. Thanks again.
Very good, this es the only one that so far Made me undertand about event handlers, I watch it every time I want to implement one
I am glad you found it useful.
Thanks Tim, now more comfortable to use events in our code.
Great!
Thanks for sharing your knowledge
You are welcome.
Thank you Tim for making C# Events so easy to understand that C# beginner can understand. I had a confusion though:
Am I right in saying that, removal of Events such as recordTransactionsButton_Click, errorMessage_Click is taken care of by Visual Studio but the events such as TransactionApprovedEvent, OverdraftEvent that we create must be removed by us.
Also, where in the code should I put customer.CheckingAccount.OverdraftEvent -= CheckingAccount_OverdraftEvent; to remove CheckingAccount_OverdraftEvent?
Hi Tim, May I ask why we need to use IReadOnlyList for Transactions? This property (Transactions) do not have set for outside of class to change the value.
To prevent another programmer in the bank accidentally/intentionally modifying a list that comes from that class. It is not powerful protection by itself (because you can make anew list with the same contents) against error/fraud but once you combine it with the full suite of fraud/error controls at the bank it becomes more useful.
@@michaelnurse9089 Ok yours makes sense but makeing a property type just IList ( instead of IReadOnlyList) and returning _transactions.AsReadOnly () in getter will not be sufficient protection. I mean if we return _transaction.AsReadOnly() in getter, why we should use IReadOnlyList type rather than just regular IList ???
Thanks alot Tim, keep up the great work, you are fantastic.
Thanks for trusting Tim.
Great tutorial. Would you recommend this approach in a blazor client side app?
Using events? Sure.
Thanks TIm on another great tutorial. This is so simple and consise explanation of C# events.
Cheers
I'm glad you enjoyed it.
The best events tutorial i`ve ever seen. Beelive me i red and seen a lot of them, and couldn`t understand a damn thing. Thank you!
You are welcome.
IAmTimCorey Even though the other tutorials were in Russian) Imagine how good this tutorial has to be if English is my 3’rd language))) Imagine how bad is my English but still i had no problems with understanding how events work)
This is just an amazing explanation with lots of tips, thanks a lot, Tim!!
You are welcome.
Thanks for video. It really help me understand events.
You are welcome.
Hey Tim,
Great video again. I've always had trouble wrapping my head around the whole 'events' thing. In the past I've read some pretty compicated stuff, but that was all explained from the point, which is still true of course, that it all starts at the point where you get to learn about delegates, after which it gets increasingly complicated. For me, that is. But your video made it much clearer.
Just to be shure I'm doing the unsubscribing of the events the proper way, this is the code I devised for that purpose:
private void Transactions_FormClosing(object sender, FormClosingEventArgs e)
{
_customer.CheckingAccount.OverdraftEvent -= CheckingAccount_OverdraftEvent;
}
I had to go for the _customer, since customer is a function parameter of the constructor and therefore not accessible outside of that.
private void Dashboard_FormClosing(object sender, FormClosingEventArgs e)
{
customer.CheckingAccount.TransactionApprovedEvent -= CheckingAccount_TransactionApprovedEvent;
customer.SavingsAccount.TransactionApprovedEvent -= SavingsAccount_TransactionApprovedEvent;
customer.CheckingAccount.OverdraftEvent -= CheckingAccount_OverdraftEvent;
}
Or is it better to do this inside the _FormClosed event?
BTW, is there a way to check if there are memory leaks should one omit this sort of code?
Thanks,
Peter
The FormClosing event is the place to do it. You don't really need to do it in your main form, since when that form closes the application closes but that all looks right. As for checking for memory leaks, I'll be doing a video on that in the future. You can use a profiler to track your usage.
Brilliant job Tim. Thanks a lot for sharing it!
Thank you!
at 25:01, what if we just write "public EventHandler RaiseTransactionApprovedEvent;"? The code seems to work, but what are the differences?
That way exposes the EventHandler as a public field, which would allow it to be overwritten instead of just subscribed to. It is considered a dangerous practice: stackoverflow.com/a/46824847/733798 Good question.
@@IAmTimCorey totally makes sense now! Thanks!
Thank you very much I was so confused until I watched this
You are welcome.
9:40 shouldn't balance be greater than or equal to amount?
10:12 welp, nvm.
An hour long, but totally worth it.
Great!
Great video as always Tim!
Thanks!
Another great video. Now I understand events better. Thanks Tim!
Excellent.
Thank you for this video, it's really nicely put together.
I also like you clear calm way of speaking :)
Subbed
You are most welcome. Thanks for watching.
Subscribed and liked. The video is long but worth. You did make it coherent and precise. Again thank you.
You are most welcome. Thanks for watching.
Hi Cory, Really enjoyed your vids and have learned alot. I have used c before but now I am looking into the interface to my windows laptop.
At the present time I program my own devices and enjoy learning programing. I only write my own files at this time. for my stuff. Thanks again, Len
You are welcome.
Hello Tim, I started watching your videos recently and they have been very good.
I went to your patreon page and was looking through the Tiers. I think you have a small typo on the first Tier for $1:
"
Did you know paying just $1/month provides me with more income than UA-cam ads do for all of your views? So if you are wondering if this matters, is absolutely does.
"
I assume the last three words of that string are supposed to be "it absolutely does" instead of "is absolutely does".
Just thought you would like to know. Thanks for the videos!
Thanks for the heads up. I fixed it.
Great video Tim, very simple to understand. Thanks!
You are welcome.
The communication between the two Forms and the customer class can also be done by adding bindings to the Form controls. Would you prefer to use data binding or to set up events? Thanks, Tim!
I feel that for this particular task Events would work more smoothly.
It does depend on the scenario. An event could be the right way to go. Passing a form reference can also be an option.
Cleaning and unsubscribing events I find the most challenging to avoid memory leak scenarios.
Yep, they are challenging.
@@IAmTimCorey I got caught in my own events web once or twice 😂
I like the new event shorthand notation.
It is convenient at times.
You are the best at explaining! Thank you so much!
Happy to help!
very informative and helpful. in the start to finish course, you always used the wiredup() method, does that means we can call an event there as well or eventhandler will not work there. thanks for all the good work that you put in your videos and they really are helpful.
You are most welcome. Thanks for watching.
For some reason when I enter 175 or any amount more than my checking account and click purchase it says "withdrew 100"
Sounds like a good time to track down what is going on and fix the bug.
This happens to me also, any solution?
Nice to know about events. I guess we can use it whether windows form or wpf but i dont feel comfortable with windows forms. Drag and drop feels just not corret. Anyways, everything will be more clear on user interface section :))
I started on WinForms and doubting what to do next. I understand the feeling of it not being correct, but the WinForms designer is so easy to use for starters..
You can use Events in any part of C#, not just in the user interface.
Awesome stuff! I have a question, how could you trigger and event in the background when for example gamepad controller was connected or disconnected? I do not know where to handle the event listener that it would check if the controller is connected or not!
thanks in advance! BR
When talking about hardware, you would need to probably bring in external libraries to listen for those events.
A possible topic for upcoming videos: The Art of Clean Code (obviously in C#). What you think?
That's definitely a possibility.
at 54:03, what if we just write "public event EventHandler OverdraftEvent;" without the ""? when we invoke the event and pass an instance of OverdraftEventArgs, it appears to work fine. Is there an advantage of being specific about ?
That allows you to easily get the strong type on the other end.
Hey Tim... Just had a little query... I still don't have any idea of WPF and even Winforms... So could you please tell me how I could practice the events? I admit that it's possible to practice with the demo, but I want to apply it once myself....
I can't specifically answer that questions, but I can point you to Tim 'Intro to WPF' - ua-cam.com/video/gSfMNjWNoX0/v-deo.html Please consider checking it out!
You can create console applications and try things out. Events work fine in console. Make them trigger when something is near full - like a list or a game level is almost complete or something like that.
@@tomthelestaff-iamtimcorey7597 Thanks!
@@michaelnurse9089 Thank you so much... That's a great idea to work with!!!
33:50 I couldn't think of a way to fix the duplication, can you briefly explain what would you do here to fix it?
So, I know this is a month late, but I'll try my best to explain how you could consolidate this code. Both Account Event functions do very similar logic with very similar data types. Each resets and fills it's list boxes, and change a Text Element's value. What we could do is write another function called something like UpdateFormWithNewTransactionInfo with parameters of (ListBox box, Label label, Account account). Then we'll just put in generic code and pass in the data we actually want to change as parameters. Think something like this:
private void UpdateFormWithNewTransactionInfo(ListBox box, Label label, Account account) {
box.DataSource = null;
box.DataSource = account.Transactions;
label.Text = string.Format("{0:C2"}, account.Balance);
}
Hi Tim!
I highly appreciate you for providing us such a valuable content. I have a question about Events. For me it looks that everything you done by implementing events in this movie, may be achieved by implementing just appropiate plain functions. Is it true? Anyway, why really we should use events? I understand how they works, but i'm sure that i wouldn't be able to decide when use events, and when not in my code.
Events allow you to act in a disconnected manner. Yes, you could just create a function but then the event caller would need to know about a method on the event receiver. That creates a tight coupling. Think about Windows Forms. When you click a button, you want something to happen, right? If that button click didn't fire an event but it called a method, how would you add your code later? Microsoft created the button. They would have to know which method(s) to call when they build the button but your methods weren't created until years later.
@@IAmTimCorey great example
Hi Tim! In the real world MVC app how would you go about associating two Accounts with the Customer class? In your demo you are using Checking and Savings accounts as properties of Account type. Would you have ICollection in Customer class in MVC or two classes one is for Checking and one for Savings and then use navigation properties to each one of them?
I would probably have a List and add each into the list since you can have multiple of the same account type.
Another great video. You are super. Thanks for the Video Tim.
You are welcome.
6:30 why not just write public List transactions { get; private set; } ?
Because that public get would get you a reference of the list and you can alter that list in any way you want including adding and removing items. The private set only prevents you from exchanging the list reference in the property. A ReadOnlyList on the other hand makes the elements IN the list readonly as well, so you can get an element at an index but not set.
Max is correct.
Tim, once again - thank you! Cool lesson.
You are welcome.
Hello Tim! In this case, which one is the Publisher and which one is the Subscriber?
Is the publisher in the UI or is it the one with the .Invoke() method? And the subscriber is the one which is called with the Invoke() method?
Hi Tim!
I have a question about the first event - TransactionsApprovedEvent. Can I replace this event with a Binding Source? I mean I could declare a new Binding Source and assign it to our transactions list from Account Class. Will it work?
Of course, I would like thank you for this video. Your way of explaining C# is always awesome :)
We need a discord server for the audience of this channel so that we can question and discuss more.
That's not something I'm able to do at this time. One step at a time.
Hi Tim. Just found your video. Great work. Thanks. However, the link to source code is not working. Could you help me get the source code? Thanks.
I fixed it. It should work now.
@@IAmTimCorey thank you. I have received it.
Hi Tim, I have 2 questions
1. To understand events, do I need to understand delegates as events use delegates?
2. To understand Routed events, is it necessary to understand normal events. And can you pls tell me why do we need routed events in WPF as we can use normal events to fire up something like Button click in WPF?
You don't have to understand delegates to understand events. I actually figured out events before I ever understood delegates. However, once you understand delegates, you will better understand events.
Routed events allow you to fire the event in more places than just the caller. Personally, I wouldn't stress over one vs. the other. Here is an explanation that might help: www.wpftutorial.net/RoutedEvents.html
Tim,Thanks for the answer
Excellent teaching.
Thanks!
Many thanks for this great tutorial. Can you tell me which font you use for the text editor?
The standard one. I'm not sure specifically but I didn't change it.
I was wondering if you had any videos or recommendations to learn Add/Remove properties for multiple events. I saw it on the Microsoft website but I'm not sure of its utility nor when to use it. The whole thing with EventList and creating static read only objects
I added it to my list, thanks for the suggestion.
@@IAmTimCorey Awesome! I'd be waiting. I was also wondering if you had like a discord channel for folks who watch your videos to interact and share projects and progress
Thank you for all your videos, they've been quite helpful.
You are most welcome. Thanks for watching.
At 8:59 you had Account = null in MakePayment() would a ? For nullible have worked as well?
A litte before 32:24 when you tabbed for ApproveCustomerTransactionEvent, a function was created but on the line that you were typing there was no parenthesis. Was that a reference?
26:35 reminds me of Ternary Operator one can use in 'if' statement.
Is that what this is or is this different?
It is different (but similar looking, I agree). This checks to see if the item is null. If it is null, it stops there. If it is not null, it allows the property to be checked.
Cool, I have a question, what's the difference between event and Action? I've used the later for a Unity project but I wonder if there's a difference between the two (knowing that Unity doesn't use the latest .NET framework and that the example I had seen used two lines for the event/delegate).
Actions are delegates. Events use delegates. There is a distinction between delegates and events but it is small. I'm going to be doing a video on delegates soon, so you will more clearly see the differences and uses there.
Actions are delegates, ok! :)
Looking forward! Thanks!
Hi Tim,
is string.Format("{0:C2}", e) faster than $"{e:C2}" ?
Sigh. No, I just fell back on the "old" way of doing things instead of remembering about string interpolation. Good catch.
Tim I know you are a huge fan of using Windows when building your apps. Since the release by Microsoft dotnet core for all 3 platforms now with a little work you can not only build and run your apps within either OSX or Linux. Then on that subject build an app using the built in API with Angular. Do you have any further plans for this?
I'm currently working on a full application course where the application is built fully in .NET Core (a web-based helpdesk system). I'll be building on Windows because that is what I have but I'll surely accept the donation of a new MacBook to do videos on :-) Just note that while .NET Core runs on any platform, WinForms, WPF, and UWP do not so they can only be built in Windows and run on Windows. .NET Core 3.0 is bringing .NET Core to WinForms and WPF but they still won't run on anything but Windows (and you can't build them on anything but Windows as well). There is a benefit to making them .NET Core but it isn't about cross-platform.
I've watched this twice now as I am blown away how easy it appears to be to update the UI as a result of a method running in a separate class. How does this compare to BeginInvoke for threadsafe UI updates? Is it suitable to have several event handlers running for UI update from classes- for a small app I'm guessing it's not too resource hungry. For example- if I had a Db checking class which ran on a timer to check for data changes every second - would an event handler be the best way forward. I am coming from a almost complete beginner position and someone who has struggled with UI updates from classes and thread safety. Big love for all your videos - really learning a lot!
Events aren't really memory-hungry. There is nothing active really. They are just stored methods that get fired when they are called. An event that gets fired when an update to the database is discovered would definitely be a possible solution for your situation.
That's great thanks Tim. I've also found out how important the ? Is when invoking the event. Form1 had stopped listening and it was throwing a null exception. Had I not known about that little gem I would still be screaming at my code. Really good videos - keep up the good work.
as of till 43:00 , can you do the same thing witout these events ( i mean the ones created by us ). Like for the error shown, cant we just do it with a normal function?
Everything that can be done with events can also be done with functions. It's much less overhead, far safer and much, much easier to debug. There are exceptions like in banking where a continuous transaction record is needed, but then... if you are in one of the fields where this is necessary, this video is not the one who will teach you how it's done correctly. Your supervisors at your workplace will make sure that you are up to date on the best practices of the industry.
great video as always, can you explain the reference leak caused by events?
Here you go: stackoverflow.com/a/4526840/733798
@@IAmTimCorey thank you sir but i would rather that you consider making a video about this topic because you know how to explain things and make it easy to understand fankly i read a ton of articles but i couldn't get what i need especially the best practice when it comes to this problem
Thank you Mr. Tim and I have question ?! can I use event in database object on property change value make auto update something updated directly to database
You can use an event method to update a database. You will need to manually develop what the update does, though.
@@IAmTimCorey
Thank you for answering my question.
Can you make example with three tires application dal, bi and ui
With genral repository and unit of work
Thank you
Thank you! I have reinforced my Events handling knowledge.
I'm glad it reinforced some things for you.
hi, Tim.
Good video. But what is Event accessors ("add" and "remove") ?
Add allows us to add an event endpoint and remove allows us to remove it.
What is The Advantage of Delegate and Events in C# Tim
They are another tool in the toolbox.
Thanks a lot for uploading this video . I was struggling to understand how events work underhood before watching this video . Where do we write the code for cancelling the events ? Is it in finally block or as well as exceptions
I assume you mean cancelling the event going forward (so if this is the first method called, the others don't get called). That can be tricky since you don't know what order you are in necessarily (are you first, are you last, or are you in the middle somewhere). The actual call to cancel the event can be anywhere you want it to be. However, I don't think you will get much benefit from doing so. Cancelling a keyboard event (keypress) is a thing because you know your event is fired before the key is processed. Therefore, cancelling the event cancels the standard key press action. In almost every other case, cancel just makes your application less predictable. Remember that the event that triggered the event calls already happened. You aren't cancelling that action. Just the rest of the responses to it.
Thanks for your reply . You mentioned about memory leaks if we don’t de register the events . Can you please explain how to do this
I strive to be as good as tim corey
He sets a high bar!
Tim, one of my friends was asked a question in interview like whats advantages of events over delegates?
Isn't it wrong question to ask this. Events use delegates to work. But how can we compare them?
There is little difference between events and delegates. Events add a bit of protection on the top of delegates and they serve a bit different purpose (alerting a listener vs using code from somewhere else). For most purposes beyond minor quibbles, there isn't really a difference.
Great video on events.
Thanks!
Could you please give me an example of how to remove the events discussed in this tutorial ? to avoid memory leak and be more like a good citizen :)
I will add it to the list. Thanks for the suggestion.
not an expert but I usually do -= eventName which is how it is shown in UWP and Xamarin docs
Thanks a million for such quality education! You're awesome!
Thank you!
This video really helped me a lot, Thank you so much!
You are welcome.