C# Events - Creating and Consuming Events in Your Application

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
you almost certainly know what events are in c-sharp even if you don't you've probably used them before what you may not know is how to create your own events in this video I'm gonna introduce you to events and walk you through creating your own events we will also discuss the features we can take advantage of and what the best practices are we should know about if you're new to this channel my name is Tim Corrie and it's my goal to make learning c-sharp easier this channel is full of videos explain the various parts of c-sharp there's even a full course on building applications from scratch I hope you find it useful and if you do don't forget to subscribe and hit that little bell icon to get notified when I release a new video every Monday there's also a link to my mailing list you can sign up for in the description below that will keep you informed of all the training resources that I'm creating for those of you who have found this channel useful I'd appreciate it if you check out my patreon page if you become a supporter you can get exclusive behind-the-scenes access also everyone who is a supporter at any level will get access to the gold rewards when we hit them those rewards include a tour of my office a documentary on how I make videos and even a full course the link to patreon is in the description below alright so let's tackle events here we have a starter application so we can jump right into looking events if you want the source code fest video the link in the description below will take you to my blog where you can see the download links for both the starter code as well as a finish code once we're done now what if Korea is a simple banking application in windows forms now when I say simple banking application I mean this is a sample this is a demo this is not production code so don't take this and try and make it into a real application that well just start over alright but what this is real simple we have one customer we're not going to try and create customers and all the rest we have one customer and we'll say who that customer is what their checking account balance is and what their savings account balance is we're also going to see a list of their transactions in our checking account and their savings account now we have this button here that says record transactions and that will open up this form right here which allows us to make purchases it's going to simulate a credit card machine yes it is the same name a customer you got type in an amount here and say make it purchase and it's gonna simulate making it purchase which should go into the checking account transaction list now one of the features of our specific banking demo is the idea that if you run out of money in your checking account and say you have $10 left and you spend $100 what will happen is it will look at your savings account and say yes I can cover that other $90 from my saving account so I'll move money over i'm savings in checking and allow that to clear they will also post this message here saying you have an overdraft protection transfer of $90 all right so no lathis hidden okay so that's the basic design of this system just two forms and that's it now behind the scenes let's look at what happens so let's go to the code behind for the dashboard and we'll see we create the very thing first we do is create a new customer object and a customer is just a class with three properties the customer name and two accounts to account obvious ones a checking account one that's saving account I guess is where I say demo code because I would never hard code it to say this is your checking account well if you have to well if you have three well if you have different kinds of account besides just checking your savings and what if those behave differently right now they're both just account objects so again just demo but I won't point it out all right so the account object is pretty straightforward we have an account name we have a balance now a balance is a type decimal because whenever you deal with money you always want to be decimal not double if decimal is precise double is not and for that I have a private set meaning if you're outside its class you can see the balance usually get but you cannot set the balance instead it's handled it elsewhere and I'll show you where in just a minute then I have this private list of string called transactions all right so it's private so it can all be seen inside the account class and this is actually the underscore here indicates it's a private vacuum field meaning this supports a full property so it's a list of string it all this is gonna be is a string that says you made withdrawal of this much money for this purpose that's it and if you listed those or a deposit of this much money for this purpose now this one gets a little trickier this is the actual public property that takes this transactions variable and uses it it's called transactions but returns an I read only list of string not a string or list of string and the difference there is our i read-only list does not allow the user to make changes to the list it just throws in to read it which is what you want because you don't want the user to make changes to your list of transactions that's for this class to do so we return that transactions which is a list of string as read-only that's baked into the c-sharp framework that you can do that notice I have no set here just and get that's because this is me an I read only list well you probably can't make a modification to a read-only list right so instead will happen is unlike normal banking fields or actually I make modifications right to this private banking field instead of going through the property so that allows us internally to make changes to the list well externally it's read-only so that's kind of a side benefit of this video it's you know it's just a little bit extra information I just want to kind of explain why I was doing it that way all right we had a couple of methods here let's let's close this down see and see him we have two methods one called add deposit and one called make payment these are probably pretty standard things now this is one of those areas where I made a deviation from where what a normal banking application might do normal banking applications typically have one entry point and they just mark the the information as either a debit or a credit and they change the sign from positive a negative it all goes into one kind of column and that I find a little bit confusing I want to kind of break those two apart this was a little more clear what's going on I like the confusion as adding to this demo especially when I wasn't really a part of the primary purpose we're doing this demo for all right so let's look at the add deposit so this it's gonna be putting money into this account so the first thing it does is it adds to the transactions list okay it's gonna add this string and the string is deposited this amount and this is a dollar sign format so string dot format and this particular format says it's getting currency and it's going to be two decimal places and here is the actual thing to format which is the amount being passed in so deposited this amount for and there's the deposit name that's gonna be you know initial deposit or add more money to savings whatever we want call it next we have the make payment method make payments a little bit trickier so we have here to pass in a payment name which the same as deposit name is payment instead the amount that's but the same but then we pass in potentially a backup account and by default that is null meaning we can not pass in this third value and it will still work because it'll put the value default layout null in that variable this is going to allow us to have that followed by account if we go below zero or would go below zero with a certain transaction so let's walk this through so first it says my balance which is again that's that property right here so it's got a private set it's got a public get to say is if my balance is greater than the amount you want to take out me I have a hundred dollars you want ten no problem let's go ahead and withdraw that information same basic format it just says withdrew instead of up here it said deposited all right so withdrew this amount for this payment name it take also takes our balance and subtracts that amount so you have a minus equals which says balance the equivalent balance equals balance minus amount that's the minus equals does and finally we return true and then return true says this worked all right so that's the the perfect scenario the idea we have enough money we don't ask from where we have it just works however if the amount is greater than the balance and actually you know what which make one change here greater than equal to if you have ten dollars and you want to spend ten dollars no problem that's one one quirk in the original let's go ahead and save that all right so we don't have enough money if we hit this l statement so we don't have enough money let's check for a backup account if it's not null that means we have a backup account here we're going to do now let's skip down to the else first just a process what's gonna happen if the backup account is null so skip down here yet the backup account is null we just say nope it failed and return false meaning we couldn't do it so that's that's just what happens if we fail this but if we have a backup account we're going to check the backup accounts balance plus our balance to see if it's greater than or equal to let's say that as well greater than equal to our amount so maybe we have $50 on our checking account we want to spend a hundred it's gonna look now to see if we have another 50 in our savings account if the two combined are a hundred dollars or more then we can go ahead and say cool let's find out the difference so the total amount you want to spend - will we have our checking account that's the amount we need from the other account so we're going to do is we're going to go our backup account and say make payment which is actually the method work right in right now every I say the payment is overdraft protection and here's the amount we need so essentially it's gonna take that money out of the backup account which normally in our case is gonna be the savings account and as long as it's exceeded so it's false the return falls mean for some reason the overdraft failed it should never fail because we do our check here first to make sure we have enough money but I just wanna put that check in and make sure but if it succeeds then we had deposit called our overdraft protection deposit into our current account great that's that's this one right here I'm gonna call this method up here and put that money from our savings account into our checking account then we're going to say we're gonna withdraw the full amount from our checking account and subtract that from balance which means at the end our balance is zero because if we had $50 in the checking account we spent a hundred we pulled 50 from savings put in a checking that's now means checking has a hundred savings head is fifty less then we withdraw a hundred from checking leaving with zero all right and we say the transaction worked so we have this overdraft thing happening but we're still able to process the transaction so that's all the account does it has a make payment and add deposit that's pretty much it okay so back on the transaction let's go back to the dashboard real quick make sure you've covered that so we have our customer we first set up we load testing data which means I create a customer name and then a checking and saving account and then I say I name them so Tim's checking and Tim savings and then I add deposits to both so checking account gets an initial balance of one hundred fifty five dollars and forty three cents and that am at the end indicates that it's a decimal not a double if I didn't have that there they try and put double into a decimal value and that won't work so you have to specify that capital M to say this is actually a decimal value you don't have to do that if it's a if it's a variable but if it's a static constant like an actual just you know typed out number like this you have to put that capital MV end so we have an add deposit for a checking account and one for a saving account both initial balances different amounts just kind of rally picked next after I load the testing data I'll minimize that now I call the form wire up and the form wire up says all right let's put the customer name into the customer text which if we look at the dashboard is you know right here and then we'll do the same thing for the let's wire out the data sources for checking transactions and savings transactions we just link that right to our read-only list and that's fine we can do that in the checking account balance value and a saving account balance value there tax we put beginning at string dot format so we have a dollar sign all the rest and that's our checking account balance and say account balance so all that being said it basically populates this form these these two lists here these three labels here and we're all set this by the way is is hidden now when we click this button right here to record transactions we create a new transactions object a new instance of it which is a form this form right here and a pass in that customer class so the customer class how do we have we pass that in and then we show and I'll get to that in just in it the last thing we have here is the error message click so this this red box right here what happens is if you see this and you click it what's going to happen is it's gonna set the visibility back to false it's gonna close it again so that's all that does all right so let's look at real quick what this transactions does and why it takes in the customer object so right click on the transactions class which is a form it brings in at through its constructor the customer class and stores it in a underscore customer private variable and the reason why is because we want to have that customer text text the customer name to put in there so that's when we look at this right here the customer name that's where that goes and then when you click the make purchase button what happens is we take the customers checking account and say make a payment it's a credit card purchase and for the amount that you specified and then we pass in a savings account as that backup account and we do capture the payment result we don't really use it right now they also set the amount value of the field so that's right here the amount we set that back to zero all right so that's it let you run this application real quick so we start off with Tim Corrie checking account and account balances and initial transactions for both we click record transaction and we say let's go 95 and make it purchase it clears it out but nothing else seems to happen ok we're address that in just a minute but if I say 95 again and 150 so it seems to kind of work but we're not sure if it is or not so let's look at first of all the events already in place and then we'll could create our own events so we can kind of monitor this this system as it works so the first event that we see really quickly is this record transactions button if we know is here in this code we have record transaction button underscore click this is probably familiar with you if you've done any kind of Windows form or to EPF work this is a click event on button usually to get this you just double click on the button and it takes you right to code this is some code that'll be called this method Li called whenever that button is clicked this is the event handler so it handles when the event is actually triggered all right and so we're kind of used to this the idea well yeah when you click this button this code gets run but the question is how does that actually work how does this code actually get called now I don't know if you know we're not like closes other ones I don't know if you know or not but in a form is actually the designer dot C S code as well so you look at the form it says that it's a partial class well the reason why you have a partial class is because we actually split the class into two pieces or Microsoft has the part that we use is the part that's okay for us to meddle with to mess with the part we don't use is the part that the my crystal studio messes with and so say things like this is generated code and you know don't modify this you see you know do not modify all right now the reality is you can but it's kind of dangerous to do so but I just want to point out in here if you see this right here this method if you want to know where that actually gets wired up come to the designer dot cs4 dashboard and if you scroll down here you'll find it and what I can do is I can do a control F and find it but it's right here actually this dot record transaction button dot click plus equal new system died event handler and then it passes in this dot record transaction button underscore click so it passes in a method to this click event which doesn't really give you a whole lot of insight necessarily but at least it shows you one level up what's happening but let's figure out what this is and how we can create our own we've this is this is pretty important stuff to kind of grasp because if you can make your own there's a ton of stuff you can do so let's start off by making our own alright so let's go to the accounts class because this is where I think we need to kick off the events so an event has two parts to it it has a place that triggers the event it has the place or places that consume that event so for example a button the place that kicks it off is when the mouse left clicks down on that particular item on the forum usually a button that's what triggers the event and then the other side what consumes that event or what listens to that event is the button click event code where it says okay open a new forum or do this or that so this is the place right off a couple different events and so let's create them and as we do we'll talk through what they do so the first we want to create is I want to create one where we say okay a transaction has been approved for this account doesn't manifest account is checking your savings all you wanna know is that we did something so we wrote this transactions list and the reason that's valuable is because we can listen to the event back our dashboard form and say whenever we have a modification to the transaction list or the balance I want you to refresh the screen to show those new transactions because we remember when we actually opened up the the transaction form and started doing transactions nothing seemed to change and the reason why is it never knew to change so let's create an event like I said for the whenever we have an approved transaction meaning if you're not going to approve a transaction nothing actually gets changed then don't trigger it only approve once so the very top of our public class account I'm going to create a new it's gonna look like a public variable not a property and that's actually intentional and the way you do it okay this is a one-time I'm gonna say creates me it looks like a public variable alright so public event where I say event handler and I use the generic version alright the generic version means has that these angle brackets here okay so this seems you that the the easiest way of going about it and it's also the I think the one going forward that the most people will use so inside here we pass in a type that where I'll return back information about the event let's start really simple and I'm just gonna say string there's gonna pass back a string of information that's it and we'll look what the information is and how it works and then we're actually elevate that's the next level if you want later all right I'm gonna call this event raise transaction approved event all right so raise transaction approved event well that's going to say is when people listen to this event if it gets triggered a transaction has been approved essentially alright so that's all we need to do to clear an event handler that's kind of that middle piece so again we have two sides we have what kicks off an event and then we have what listens the event in between is this event handler that allows you to say and then it's happened and it allows you to say it allows you to listen for that event so now let's go down and find a place where we actually have a change to our our transactions so right here we have a deposit so after the balance has been changed I'm going to raise a new event I say raise transaction approved event now here's a little bit of a tricky bit question mark dot invoke I'll explain in just a minute first thing you pass in is who the sender is notice as object object sender so saying who is that the was a thing that triggered this event well it's this this class and so you type at this and that usually works no matter where you are because that's who was actually saying the event the notice says string e well that's because we said right here that the event handler is of type string so in this case we're going to say is just the deposit name so this deposit is what was just recently added and that's what triggered the raise transaction approved event now I said come back to this and I definitely will the question mark what does that do well so here's if you've seen event handling set before and in the past you may have seen a much more complicated design here because they actually have usually about you have one line that assigns a new variable and they have a null check in if statement if the null check is not true then it keeps going on so the reason why is because when we trigger events we only trigger them if someone's listening so there's no point in saying hey something new happened if no one cares so this way it saves us some cycles and saves us some some data says it's in processing if we don't trigger that if no one's listening in fact if you were to trigger it and it's null it caused a problem to cause an exception so you have to check first to see if this is not null if it's not null then you can invoke it so this question mark what does is it says if this is if this right here is null stop right here don't do anything but if it's not null continue on as if the question mark wasn't there and that allows us to do a quick null check and immediately invoke the the event the reason why is really powerful is because previously we actually had a copy us to a new variable and do a null check on it because the fact that what would happen is there might be a race condition where between it's how we checked for null and actually then trigger the event a person would have stopped listening the last person was stopped listening and it would be null after all and so it caused a problem throwing exception this way it's all right in line and it allows us to immediately continue on if it's not null and there is no race condition so if you see other code that has multiple lines that do a check for this first and before you vote invoke just know that that's still valid code but it's no longer necessary code and there's a better way of doing it it's just this is a newer way I believe c-sharp 6.0 with let us changed so just note that difference there so that's all there is I has triggered the event to say I deposited something all right I change the transaction all right a copy this I've got a few more places where we change the transactions right here but we're not depositing something we are making a payment all right so that's right there where we have the subtraction of the balance and the a a new transaction will raise that event again let's scroll down here and again we have this balance change therefore we're going to raise that event and that's it so that's all the places where we have something going on we're changing the transaction list and we're changing the balance so now we can order the dashboard now in our wire up form we can actually start listening to those events so we can say customer which is our our customer object we have a checking account and notice down here we now have as lightning bolt next to raise transaction approved event all right now you could call that instead of raise transaction prove let's just call it transaction approved amount let there raise all right so let's just back up real quick if you make a mistake like this or want tweak something do it as soon as possible rather than trying to wait until later all right let's rename that and that should rename all of them that's great and now we can do the transaction approved event all right we could drop the event off we wanted to just say transaction approved but transaction approved event is a little more clear so that lightning bolt to left oh it says this is an event now that event how you wire it up because you say okay that's the again the glue that holds the two pieces together the I'm firing off the event and I'm listening to the event so how you add one or more things to the I'm listening is to say take that same event object and just say plus equals and then Otis it it's allowing me to have press tab to insert this default name checking account underscore transaction approved event sure sounds good I hit apply what that does it creates a new private void method that takes in two things object sender and string e that sound familiar it probably should that was what the two values were that were being sent to this event we sent this which was the the account class instance and we sent which transaction it was now here it says throw new not implemented exception that's the Microsoft standard so that we can continue on compiler code but if you actually were a trigger this event it's gonna crash the application because you have not yet put real code in here so let's put real code in here the real code is going to be we want to reset that checking transaction list so this data source right here we're gonna set the back up as the checking account transactions but we also first me a set to know that's what it clears it out and that sets it back to that same list it will re-evaluate it and put the correct value there also we want to grab this checking account balance and update it as well now let's do it again for the savings account and then we'll actually see in action alright so customer die savings account dot transaction approved event plus equals I hit tab to create that event and it's the same basic premise here we get rid of this when I grab our savings account data source now where I say the first one is said null let's say it one sets it back to that list and finally we need to grab and update the balance all right now again there's a sample code there's there's some duplication here we could definitely take care of them clean up but for the sake of this demo I'm gonna try and keep it simple alright so now I have the other side of the event I have over here the trigger this was saying something happened over here is the listener that says okay when this particular thing happens do this and this particular thing happens do this let's see us in action alright so there's our our standard form we'll hit record transaction and we'll say I want to withdraw $85 make the purchase notice my checking account balance has now changed and I was drawn eight hours for a credit card purchase let's do again see what happens when we withdraw to 85 is time which is more than a checking account balance notice we actually have a few transactions now we deposited nine dollars and fifty seven cents for overdamped draft protection and we withdrew eighty five dollars total from our checking account leaving it at zero dollars now our savings balance is eighty eight dollars an 88 cents which I really didn't plant that's pretty impressive okay so now let's draw with draw another $85 when they get $87 that deposited 87 dollars of overdraft protection from our savings account and then withdrew that amount for the credit card purchase leaving our saving account at one dollar and eighty eight cents and notice also in the saving account transaction we also have these as well now the very idea that this is updating over here tells us that both events are firing it's the only way we update the savings transactions is whenever these savings account changes the same with checking and so actually in one one move so I withdrew that money it's actually withdrawing money from savings which triggers an event it's adding my checking which triggers an event and it is then the drawing a whole mine now whole Mount now I actually don't trigger the event twice over here because the fact that I wait okay I say yeah I know I'm doing both I'll trigger the whole thing once the whole thing is done now just in case you're curious what happens if I would draw two more dollars which I don't have and I make purchase nothing happens because I can't so that's really all there is to events the idea that you create this event handler which is just so I said event handler and what type you want returned and then the actual event itself now let's let's do one more thing I've read to put a breakpoint here let's run this again now record transaction and it doesn't matter I'll just put 51 dollars all right so this is triggered the checking account transaction approved event so let's look at what's sending us it's sending us an account which is Tim's checking account the balance is a hundred and four dollars and 43 cents it has two transactions one of which is withdrew fifty one dollars for credit card purchase so that's sending us the the checking account object we also have this credit card purchase as coin through as II that's the item that was the last thing that has happened that's what triggered this event so that's the information you send back which as you might expect can be quite valuable you can send back a whole class here which we'll do soon of information that way you can have a bunch of extra stuff coming along with this event to say okay this is what happened and here's all the information around it alright so that's it hit continue and we'll actually stop this right here we don't need to continue any further on that now let's create one more event let's create a new event here and we're I called this the public event and it's the event handler like I do the of T so in this one we're going to call let's make it first we'll make a decimal the type and we'll call this the overdraft event okay so this is going to trigger whenever there's an overdraft now let's go down and look at the only place where there is an overdraft and that's right here so overdraft successful so this is where the actual overdraft happens so right down here we're actually going to trigger a second event so you have event for the transactions been approved but now let's trigger another event overdraft event question mark dot invoke this and let's pass in the the amount that we overdrafted so the amount we needed all right let's start with this and now on the dashboard side we don't wire that up so say customer dot checking account Dodd's overdraft event plus equal tab enter and that creates our event method now you could create manually so you could just you know type us all out but it just it's so much simpler to have it create for you who's also names it pretty pretty well so I asked Korea just as it is now in this event let's do this let's say the error message dot text and that's our label on the front of our form so if we go to the dashboard form this is the error message text right and let's put a dollar sign from here a formatted string surest say you had an overdraft protection transfer of and when I say how much we had to transfer over so strained out format this again is that special formatting 0 colon capital C 2 that says give me a a currency the decimal point of two and we'll pass in II get that decimal e that sort of passing in and now we need to close our curly braces there and that should be it for that and we'll show that so error message dot visible equals true okay so what's going to happen is when you trigger an overdraft we're gonna pop off this red warning message on screen saying you had an overdraft protection transfer of just kind of call it out and let people know that that something important has happened so let's start this will record a transactions and let's do a big one so let's say oh one seventy-five eighty seven which is more than a checking account balance make the purchase it does a transfer and says you had an overdraft protection transfer of twenty dollars and forty four cents I click that and it goes away again that's an event that I wired up they just remove that from visibility when you acknowledge it so again I can do another transfer and bring it back because again I'm over drafting now they have a checking account balance of zero okay so I've wired up a second event but what if you wanna see that on this other form before we go on let's let's go ahead and make one modification to this form it's not Center parent it is Center screen that's why it's it's starting up off screen so this one starts on screen and Allison starts on screen - there we go that's bugging me okay so let's get back to to this let's add a similar label so we have a dashboard so let's actually copy this to this form and we'll do it right down here so I'll paste this instead of having this whole long thing we'll just say you are over drafting that's it I'll just put that ready to button okay and we're not gonna do the whole click and go the Waze thing well I could hear so we'll start off with being invisible so if there's well as false now add this event error message underscore click where I say error message dot visible equals false so if you click on it it sets the back to false okay and now we're going to without doing anything else to our account code we're gonna listen to these same event that we're already listening to on the dashboard so we wire up the initial we bring the customer in we're gonna say onto our customer dot let's grab the checking account and say we're gonna listen for the overdraft event so plus equal tab enter and that creates our our method for us and we're gonna say error message visible equals true so all we're going to do is show that error message I'm doing this just to kind of show you that there's you can actually listen multiple spots different forms you might not even have both of them open at the same time and it's a visible at the same time and it's okay they'll still fire so let's record transactions it will kind of rearrange a screen C and C both evenly don't have to and again I'm gonna say 175 which is over my checking account balance make purchase notice both actually all three by two one two and three the events have fired we had a savings account has changed its list and balance we had checking account has changed list and balance and we had an overdraft event and the overdraft event actually fired on both screens so that's just kind of down straight you can listen to an event from multiple different points in your application and have different things happen based upon who's listening and why alright so that's the basics of events but it's definitely much much more they can go into and we should so let's talk through the different pieces that we need of events first of all this plus equals seems to also indicate something else and does the fact that we can add something to this event means we can also take something away that's actually really important because you need to remove your listeners from an event before you destroy a class instance now there's some kind of cleanup stuff that can happen in the background sometimes but the reality is if you don't remove your event listeners before you close a forum there may be a case where your forum kinda half stays open in memory and isn't garbage collected which means you'll actually have some memory leakage in your application so before you close out of say this forum right here what I would do is have an event for the unclose where I just basically copy this line right here and do minus equals and remove this named method from the listeners and that's just being a good citizen clean up your application and making sure that you don't have a memory leak what that also means is that why you can use anonymous functions here meaning functions you create on the fly you don't have an actual name to them the problem is you can't then easily remove that function and so therefore you can't be a good citizen and therefore you will have some memory leak issues so my encouragement to you is don't use anonymous functions here use an actual function name and then at the close of your application just run all the event listeners backwards so underscore customer dot checking account that overdraft event - equals checking account on a score over direct event done now it's no longer listening now you can release that from memory and make sure that the events aren't firing when they don't need to be and it just makes things a whole lot cleaner so that's one thing next you saw when I create the event handlers I passed in string and decimal that's actually an uncommon way of triggering an event or what data to pass through an event typically you pass a class and I have officially a class instance and I set one of those up for the overdraft event in just a minute but you don't have to it used to be that any object I passed in here had to inherit from event orgs that is no longer the case again I believe it was c-sharp 6.0 I'm not positive on that one but they took away that requirement you don't have to there are some benefits to inheriting whatever obviously pass through here from event args one of them being that they can all be treated as event args and second you can when you're passing the value through so this right here you can actually say event args dot empty and pass in basically no event arts so you don't have a no problems past event argos not empty that doesn't work if it's not inheriting from type event args so let's set up a class to actually pass through instead of decimal for our overdraft event they also want to demonstrate some stuff you should and should not do with a class so on demo library right-click and say add new class and we're going to call this the overdraft events event arts call it overdraft event ours and we are going and here it from event marks public there we go now that's really add anything to your class it's really an empty class I'm not sure it has anything in it we can actually take a peek at real quick all right so it's got the empty method and it's got a constructor and that's it okay so that's really all it has in there it's really pretty much empty so in here we can have normal properties that we send through but that's not really what we want all right I'm gonna show you why so let's do a a prop here and we're going to pass through a couple pieces of information so right now we have an amount so let's pass in the decimal and amount overdrafted and that's gonna be our how much we went over our checking account balance and then let's pass in I don't know a string and more info okay that's it but what you want to do is set these two private sets okay and you want to pass in to the constructor ctor tab twice pass in those values so decimal amount overdrafted and string more info and then just say amount overdrafted equals that property or that parameter and then more info equals that same parameter and then we're done the reason you do that is because a class instance don't forget when you pass that around it's like rain down a piece of paper the address to a house and passing that around everybody is pointing to the same house the same part of the block the same physical address so if someone were to make a change to that house may they open the front door and sit down the easy chair well now everybody's version of that house is still pointing the same address so they all see the person sitting the easy chair that's a problem if you're making modifications and events okay and I'll explain I'll show kind Eman straight that for so let's do this let's not make them private sets and let's take off this constructor we're going to pass around full kits and sets okay and now what I'll do is go back to the account class and I want to say instead of decimal it's overdraft event ARC's that's gonna yell at me down here you can't just pass in this I'm gonna say new or we're going to event args and the amount overdrafted equals amount needed and the extra more information equals there's extra info and clothing like pretty brace okay so that's the information I pass back now let's go over to the two places that I use this let's close all but this and let's look at the dashboards code behind and right here it's a yelling at me because it says that won't work because you're passing in decimal well instead it should be overdraft event marks and that works we're going to say e dot amount overdrafted okay and then in transactions we have to go over missile you do you're here events one through the right way because you got a chain DS all over the place overdraft event are is e and nothing else needed change there so it should still all still work let's just verify that's the case so record transaction if we say 175 make purchase overdraft pops up both spots so we're good there but now let's put breakpoints in both of these events in the listeners and I'm gonna make a modification in one of them so let's start this off record transaction I'll say 175 make purchase so the first one that gets hit is the checking account overdraft event let's step over this code right here so we've written our message you have an overdraft protection of $19.57 oh you know what that's not quite right let's me a lot of occasions that instead of 1957 it's actually 38 57 and I hit continue now it goes the other form and it's overdraft event and notice let's look at e the amount is 38 57 that's what I change it to that's a problem okay in fact let's illustrate us a little more cleanly by making the changes in the code so if I were say in this first event we know now that this event fires first e dot amount overdraft that equals oh I don't know a thousand twenty dollars and forty cents so I changed the amount overdrafted to this large huge amount and then over in transactions we're going to look at what that value is okay so you record transaction 175 make the purchase we run this go to the e in overdraft and look and the amount overdraft is a thousand twenty dollars and forty cents so you see why we can't have these read/write properties because the first event can actually change the first event handler can change those values and affect all the other event handlers so that's a problem so how you solve that is by going to the overdraft class and saying actually we want to have I can't do that undo let's try to do that private sets and you have to set this through the constructor that's the only way you can set these values now in our accounts instead of saying well set those properties here we pass them in as parameters of our constructor so now new overdraft Ark's open paren past the two values in and that's it now notice I haven't changed my code so right here I try to make a change and goes you can't make a change to a read-only property therefore I can't do that therefore I've protected now all of my values so if I run this I go 175 no matter what happens I look at the value and it still says $19.57 there has been no change so that's the benefit of having read-only properties but before you start saying you should never have readwrite properties there is an exception and that exception is you could listen back after the event you could listen to say did you want me to cancel this transaction so for example in our overdraft event ARC's what if we create a property prop bool cancel transaction equals false by default so at fault that's a false meaning don't cancel a transaction but know as it has both a public get and a public set now in our dashboard we can say you know what we're not gonna allow overdrafts so you'd say error message oops I'm sorry e dot cancel transaction equals true okay so we'll still shallow will still show the overdraft attempt but we're not gonna allow it to go through now will rework our code a little bit here because we've already done the work of our overdraft so let's move the overdraft up to the top here after we check to make sure we can do it and we don't have a mount needed so let's actually move it down a little bit so let's move it after amount needed but before we actually do the payment all right we can say if now we create a new variable here on the fly but instead we're going to do is say overdraft event args args equals and we'll take this right here and control exit out and put our exams place so now we've done is we've done two steps so you first created the the class instance for the overdraft event args then we passed it in but again remember how how this works I have created right here a house and all this variable holds is the address to that house and so I have passed that address to the invoke function which then dashboard and transactions will both get that address and they can look at the house because they know where it gives the map but that also means I still know where that house is which means I can say down here args dot cancel transaction equals true so if you've tripped that to say now it's true if anybody has then return false remember it we return false is what we do if we can't do this transaction so let's run it again record transaction now notice remember I've turned off overdraft ability so 175 make the purchase it says I would have overdrafted $19.57 but nothing has happened to the checking account or a savings account lists or their balances because I'm not allowed to do it just to make this a little more like a real application and I hesitate to do this but I'm going to because I hate having total sample applications let's bring over a checkbox and we're gonna say this checkbox properties will call this the allow overdraft let's do it deny overdraft that way true is true and false is false and I'll show you why in a minute so the the value is going to be false to start and we're going to say deny overdraft ability let's call stop overdrafts as a little simpler stop overdrafts alright I'll go a bit checked property the checked property is false it's unchecked so now if we go to the the code behind for this this canceled transaction is actually going to be deny overdraft dot checked so if you checked that box we're going to cancel a transaction if it's an overdraft transaction all right so we're not just we're going to stop overdraft now check the box and I say 175 make the purchase your overdrafting but nothing's happening but now let's uncheck the box and say 175 and it goes through but it does say your overdrafting okay so that's how you can actually utilize the both the read and write properties of a property to your advantage so you can actually listen for the changes to this you you're calling code to see if someone told you to stop alternatively you could say continued transaction and one of the that said it's a true or you could say it's set the true normally but someone has to say no it's false meaning stop it so it's a lot ways you can kind of tweak that or you could have other types of properties in here not as boolean you could have numbers you could have strings whatever you want to do to listen back at the caller side to see if you should continue or to see if you should tweak something or modify something or maybe even if you have this this transaction it says hey I don't have enough money you might even Beulah send a whole account back to say well take it from here so that's the basics of events that's kind of the pitfall to look out for that's the the best practice is to to look out for and to do make sure you remove your events if you're no longer listening to them before you close an object you don't have to inherit from event art anymore but if you do there are some benefits so kind of weigh that out I would by default inherit from event args unless you have a reason not to but if you do a class and you probably should just because of all the extra benefits you can have with that class then make sure you have private sets on everything that should not be changed if it should be changed or can be changed by one or more listeners then that's fine okay then they'll allow that but if it should not be changed make them private sets and pass in through the constructor those values okay also when you actually create the event the first thing you need to do is have the the thing that sits in between okay memory have the the trigger the event and the listen for the event and is the thing that sits in between this is the event handler like I said a few different ways of doing this but this is the way that I recommend it's the simplest and easy to setup it's just eventhandler and what the type is that you want to pass back to the caller or to listener I'm sorry you give it a name and then you just invoke it and again you have to have or you really should have that question mark at the end of your event name to say don't invoke this if it's null so that's a really important piece don't forget that piece where your application will probably blow up not all the time but at the most critical time probably so that's a that's the overview of events that's how to set them up that's how you use them and now when you come back over here to the dashboard code and you see down here this right here you kind of understand better what's going on this is the listener to an event handler and where the actual event handler gets triggered is somewhere else entirely but that's okay we're just listening for this event to happen all right so I hope you got a better understand of how events work and I hope you're a little more comfortable now with using your own events in code in order to make your application a lot more responsive and a lot less linear and it's processing instead of I start here I end here it's I listen for things to happen and I respond to them and that's what events allow us to do I appreciate you listening thanks for watching if you can give me a thumbs up that I really appreciate it and as always I am Tim quarry
Info
Channel: IAmTimCorey
Views: 163,961
Rating: undefined out of 5
Keywords: .net, C#, Visual Studio, code, programming, tutorial, training, how to, tim corey, C# training, C# tutorial, events, C# events, creating events in c#, invoke, delegates, c# delegates, c# 6.0
Id: -1cftB9q1kQ
Channel Id: undefined
Length: 69min 13sec (4153 seconds)
Published: Mon May 14 2018
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.