Delegates in C# - A practical demonstration, including Action and Func

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
delegates in c-sharp are really powerful but most people don't know how to use them effectively if at all today I'm gonna show you what Doug gets are how to use them why they're useful and really how to take your code to the next level along the way I'll cover the special types of delegates named func and action now if all these new words seem intimidating don't worry this topic is actually really simple as foundation yes you can do some complex things with delegates but an actual delegate is absolutely simple now if you're new this channel my name is Tim quarry and it's my goal to make learning c-sharp easier this channel is full of videos explaining the various parts of c-sharp there's even a full course on building an application from scratch I hope you find this video useful and if you do don't forget to subscribe to the channel and hit the little bell icon to get notified when I release a new video every Monday also check out the link to my mailing list in the description below that will keep you informed of all the new training resources I'm creating for those of you who have found this content valuable and are financially able I'd appreciate if you check I patreon page if you become a supporter you can get exclusive behind scenes access also everyone who's a supporter at any level will get access to the goal rewards we hit them those rewards include a tour my office a documentary and how I make videos and even a full-course the link to patreon is in description below alright so let's look the demo application I've set up and if you want this application at this current state you can go to the link in the description for my blog where you'll see the download link for the starter code for this application you'll also see the code for the finishing code of its application so you can see where we started from and where we got to so what I have here is a project I'm sorry a solution with three projects the console UI which is a console application the demo library which is a class library the full net framework class library and then a winform UI to start with we're just going to concentrate on the console UI and demo library the wind form UI is for once we have a good handle on how delegates work we're gonna bring that wind form UI in to really show off the power using delegates so let's look at what we have in the the program dot C s which is open so we have this static shopping cart model called cart and we also have this method called populate cart with demo data which I call right away what that does it just puts four items in the cart as you can see for shopping cart items cereal milk strawberries and blueberries and then rough prices alright in the M indicates that this is a decimal field so you have to use an M to signify that a the actual numbers here are decimal and not double because by default they revert to double because it's much less space that takes up and that's what use for most numbers I need a decimal point but for money we really should use decimal because that's much more precise it's precise to the about 28th place or so after the decimal versus double is only precise - I think the 15th place which is still very precise it's just not nearly as precise as what you'd need for your bank account ok so the other thing that's does is we have here as console.writeline that says the total of the cart is and then it calls the cart which is that shopping cart model dot generate total and this : c2 just indicates that I want this to be a money which in since I'm in the US is going a dollar sign and it's gonna have two places after the decimal that's the two and so they'll show it formatted as money so we just run this before I we look at the class library let's just run this real quick and you'll see that it says the total for the car is 20 dollars and 64 cents now if you're doing quick calculations in your head and you look at you know three and a half and three that's six and a half that's thirteen fourteen that's 22 almost 23 that doesn't add up to twenty dots 84 so what's the difference well I'll say so this generate total is in the shopping cart model now a shopping cart model is really simple it has two things it has the the list of pride model called items and that's the the items in the cart at product model is really simple age of the item man price but the generate total is a little different so the subtotal is items dot some also takes the list of items it does a sum on the price so adds all a price of together and gets what's called a subtotal that's essentially just all those things add together but wait there's more we want to give a discount to our users who buy a certain amount of product from us so if the subtotal is greater than $100 we're gonna multiply that subtotal times 0.8 which means essentially we'll give them 20% off their order if their order is greater than $50 this is an LC if that's why doesn't run again then it multiplies it by eighty five point eight five which means a 15% discount have a sub holds greater than ten then we multiply it by 0.9 which is a 10% discount but if you're not buying at least ten dollars worth of product then it's the the raw cost is just the subtotal all right so we can actually put a breakpoint here let's do that so we can see let's actually put it right after the the sum so you can see how this works I mean it's pretty simple but I'll make sure you understand the foundation that's before you move on so a subtotal for our carts if we mouse over this is a little small but so there's 20 2.93 so that's the full price $22.90 now if we step into our code using f11 or the step into button right here where my mouse is it will step over the first if because it's not greater than 100 over the next if in into the third one this is okay subtotal time 0.9 and returns right away which means now it will right out to the console and I'm not putting into a variable first which is it's kind of a shorthand there which doesn't allow me to debug as easily but it is less lines of code so that's up to you if you wanted a shorthand way you put the method call right here or if you want for this method call into a variable then put the variable in this spot that's a little less efficient but we're talking minuscule scale but it is a little less efficient but it does give you a better picture of how to debug this application a little more simply there is a way of looking at this return using the debugging tools that's a little simpler if it's just put into a variable you can read the variable rate in the debugger okay so they continue that's we get at the end total of heartbeat 20 dollars and 64 cents all right so that's how this application works so now that we have a picture of how our application works let's talk about delegates and how it can make our life a little lives a little easier so a delegate unless it explains first and I'll show you how to use it so you can kind of see it as well a delegate and foundation all's it is is you pass in a method instead of a property or instead of a variable all right so when you're passing in the information to a method you know if we had a input here called you know into I we pass in you know a number or you know another variable well a delegate is the same kind of thing only you're passing a method in and that may seem a little weird a little strange but it has some really powerful uses so let's see it as an action so here we are calculating the subtotal but we're never showing it to the user well that might be something you wanna know what was the original total and then what discount did we give them well we could return a tuple here which is a essentially two different return values and instead of just one so you have you know return being the total and another return being a subtotal or we could do an out variable but both of those seem a little hacky especially since all you want to do is alert the user all right so you want to tell them hey you know what here's the subtotal think of this as you know certain cases where you want to just tell the user something maybe you had you know an error or issue in your application then you wanna pop up a message box or alert or something like that this is one of those two kind cases where you have some kind of alert you want give the user it's not a great idea to have your return type hold all the possible different alerts that you could have so how do you do this well the way you could do it is to create a delegate all right so in this class we're gonna create one and then make it the parameter for our method so in our class at the very top we're gonna say public delegate void it's not gonna return anything and let's say we'll call this the mention discount so I mentioned what the discount is in some way and we're gonna pass in the I'm sorry the decimal subtotal all right so what this does is it says this is the definition for a delegate think of this almost like an interface now if you haven't watched my video on interfaces you might want to brush up on that not because that's exactly what this is but it gives you a good frame of reference + interfaces are good to learn but this is a contract that says whenever you use this what's gonna work I'll like a parameter whenever you use this it's going to return void the method is and it's going to take in one decimal the actual name doesn't really matter but that's what's going to do so mention discount so in our generate total we're going to say mention discount and we'll give this a name I'm going to call it just all lowercase mention I'm sorry lowercase M mentioned discount all right so what it's going to do is it's going to pass in whatever whatever method we pass in is going to come in to this variable alright so now we can do is after we generate the subtotal we can say mention discount and pass in a subtotal which we have right here now what does that do well it calls the method mention discount which is whatever we passed in here and it passes in that decimal besides that this class has no idea what that does and that's a good thing all right so we're getting some loosely coupled applications here and by that I mean since this generate total method has no clue what this method does or where it's located anything like that so I'll show you next how to create a method to pass in here and then how this works so let's go over to the program dot C s again now in here what I'm going to do notice we have the the error here because we need a parameter we don't have yet I'm gonna do I'm gonna create a new method I'm gonna make it a private static void I'll call it sub total alert I'll pass in a decimal that's a sub total now you're probably was and this is the method I'm going to pass in here but notice it called subtotal alert first this one is called mentioned discount or you know the lowercase equivalent well that's because these two are not really related in any way the only thing that matters is that it returns void and it takes in a decimal doesn't really two things that matter as long as it fits that structure it can be used so I'll take the subtotal alert and I'll paste it in here now notice I did not put my parens no open closed paren for this method that's because you don't do that with delegates you just pass in the name of the method you're going to call because we don't have what the decimal subtotal is going to be so we couldn't put the parameter parens here we'd have to put in the the input we don't have that so we just pass in the name of the method all right now finally in says this method I'm gonna do a console.writeline and I will say dollar sign open and close the double quotes inside here I will say the subtotal is now do my curly braces and say subtotal colon C to close curly brace just so you know I mentioned before that this applies the money and makes it two decimal places long but normally I put spaces before and after inside as clear braces some people like that some people don't but you can't after this C - because it tries to read that as part of the format so you have to make sure there's no white space after the C - before the closed curly brace which makes it look really weird if you have space before so I just take it out on both sides alright so I know I've kind of rushed through it a little bit and if you're a little bit lost don't worry it'll click but essentially what I want to do I don't get this in front of you so you can see it working see how it works and hopefully that will you know pass spark that oh yeah moment for you so just to kind of recap before you run this generate total now takes in a method which is called a delegate all right but it's called you know that delegate was called mentioned discount that's the name we give it the parameter name would give it and we can call that method passing in the decimal subtotal over here we declared the method in our program dot C as the console application and we you know again taking that decimal subtotal and are going to do a console dot write line and say the subtotal is and and there you go so even though the demo library doesn't know anything about console UI doesn't know a thing about the console it can still call a method inside the console because we passed it through our method now just to be clear here if you're it all familiar as programming and threaded programming this is not thread safe right now because I'm calling a UI thread in this delegate which is fine unless you do asynchronous programming with this specific piece in which case you'll have to do some checking to see if you need to invoke first I'll cover that in a future async video I have one more ado I think I'll be covering using delegates in an asynchronous way in that video all right so let's run this thing and see how it works all right there we go it says the subtotal is $22.90 the toe of the car is twenty dollars and 64 cents so it ran this this method even though it was in the console application not the library where it was actually executed from all right so that's how delegates work delegates are essentially just methods you pass around and can execute in other locations and because it just matters a the signature what it returns and what it passes in we don't even have to have the coupling of knowing any kind of intermediate class structure or some kind of this is how it's going to look and work and anything where it's kind of tying things together this is really loosely coupled cause you need to know is it's a method that returns void and passes in a decimal that's it so that's pretty simple stuff we're just passing a method around that's all we're doing now let's take it a little bit to the next level by looking at func and action which are essentially just shortcuts for us so Microsoft has created some shortcuts that use generics to make our lies a little easier in most cases so let's go back to the shopping cart model now if you look at this for a at the time you've probably noticed that there's something not really good here and that is this method right here generate total and the reason is it's not really good is because we have a whole bunch of hard-coded items and that's not really wise because what's gonna happen is you're gonna put this application into production and the day after almost barely similarly the day after hopefully the day for but units not usually wait until after the day after goes on production your boss is gonna come to you and say you know what we're running a different kind of sale and now if it is over twenty dollars they get ninety percent or ten percent off and if it's over ten dollars they get five percent off it's what you have to do is come back in this code and you have to modify it again put another else tape in here if else--if and say change this one make it ninety five and then because you know 20 and then put another one in here that's ten and ninety five and it's just a complicated thing that you have a dudes you have to actually modify code and recompile everything and redeploy it retest everything and then push the production that's not the wisest way of doing things especially if as it should be this is in a library because this library may be used by 10 12 15 different applications in your company well if you have to recompile this library with new code that means that you have to change all your applications by recompiling them and redeploying them and that's really not efficient now we could pass in these as variables so you know greater than what and what's the the percent but what if you have one versus four or five different levels well then your head of some kind of you know dictionary where you have the different levels you have to have somehow some kind of loop goes through it but then what if you decide I'm gonna change things entirely and not do it based upon how much how many dollars are in your shopping cart but how many items are in your shopping cart well that wouldn't work if they rewrite the application and that isn't a good plan if we looked at our design patterns video on solid the open closed principle says that we shouldn't be making changes this this application or this class if we can help it now you could argue this is the one reason to change but we can actually change it so that there's almost zero reason to change or close to it the silly reason to change will be much less no we're gonna do that is through a delegate all right so this calculating the subtotal that's fine we're just doing a calculation here now notice I'm gonna point us out real quick I'm gonna come back to how you do this but this sum right here we mouse over it it's actually taking in a funk of product model comma decimal what that is is a delegate so this right here is actually using a delegate called funk it's one of our special types of delegates we're gonna come back to how we do this but just see I just want to point that out we're actually already using a delegate right here all right so the Cody wanna work with is this code right here this code is subject to change quite often so how we take this out and use a delegate instead well it could declare our delegate and then pass it in here but this time we're going to use the func delegate type so I'm gonna put comma I should go on a new line here because it's being rather long here so you say func fu and see now notice it's a generic and it says it has an out T result so by default it actually has 16 overloads so that the first I guess iteration of this would be just to return something not to actually have anything passed in but that's no fun so we can actually pass in notice in t1 in t2 out T result and all the way through there's a lot of them now after 15 I don't mean 16 I don't know what you do after get 16 I thought it was limitless but might not be you may be the only illa pass in 16 different variables if that's the case you're back to creating a delegate it's just one of those limitations for this simplicity model so the func we're gonna pass in first a list of product model all right that's going to be our our shopping cart items and the reason I do that is because I want to actually have the whole list there in case I want to do something besides just work with the subtotal such well is great we'll pass that in as well we've already calculated it but just in case I wanna use that you know count of how many products are in the cart or give it this kind of a certain products in the car or any of those kind of things my passing that list of product model now again I don't put the parens here I just pass in the type so list of product model next I'm gonna pass in that subtotal you type decimal and finally I'm gonna output type decimal now be a total now notice how I want say confusing but a little confusing how its laid out with that I'm not naming these things I'm is passing in the types and that is one of those limitations now I don't know a way to rename this and I like that I think that's one of it I'll mention to Microsoft at some point but for now is just the three types so a list of product model decimal and decimal so there's no this is the items this is a subtotal and this is the total it gets returned back so func takes in up to 16 parameters as inputs and the last parameter has in the list is always the output so a func is a a method that has a return value other than void all right need to give us a name since this is the the type so the type the whole thing is the type now for our parameter it's func list of products llama decimal that's the type and we're gonna call this calculate discounted total be very clear and what the name is so that's easier to use all right now before I actually use this I'm going to cut this out so that I have it for later I'll is paste it in over in my program CS so down here I'm going to say return calculate discounted total you pass in arg1 arg2 which are my list of items which is called items so items and then the second argument is my subtotal now it's I'm returning that because this returns a decimal therefore that's my total that's what gets returned back over in program dot CS I need another method over here let's call this private static void and we call this calculate leveled discount because this is the type of discount we're calculating and I pass in a list of product model I'll call it product that's called items and a decimal that's the sub total so now oops it's not a void its decimal all right so there you go so now you have a match to our funk parameter its return to decimal it takes in two things the list of product model and the decimal now we're not using the list of product model but I wind that flexibility because actually later we're gonna use that list for something else it kind of better to plan these things out and give yourself the most wiggle room just in case all right so this case I was pretty sure this list might come in handy therefore I'm going to pass it in so I pass in this list of items I pass in the subtotal I'm using that subtotal I was in the shopping cart model but now do the calculation here so this method can now he passed into the generate total I say calculate level discount again no parens so no you open closed paren with the different variables it's just the name of the method calculate level discount so this is the method I'm passing in alright so if we run this notice that nothing has changed the subtotal is $22 and 93 cents and the total of the car is twenty dollars and 64 cents let's make some tweaks here let's make this let's say it's only a five percent discount if you have ten dollars in a cart let's just make sure that indeed does change and there you go twenty one dollars and seventy eight cents so that's different so that is go to show we are running this method now instead of having it be inside the generate total method in here all right so now this generate total gift the subtotal it mentions that and somehow alerting system and then it returns the calculation that we passed in now the difference between the the delegate we did for the mentioned discount and the func we did for the calculate discounted total is that for the delegate we actually had it declare it up here and that's kind of our interface I said okay here's how it's going to look here's a signature so that then they could use that signature in other places to make sure that it truly did match up with this funk we don't have to create that signature what it does mean is that every time we use this we have to declare this whole line instead of just this mention discount which doesn't have the return type or the input type and so it's a little bit shorter so it's up to you which one you use to pay that circumstances and depending on how complicated your application is the other thing that func doesn't do is it doesn't work without parameters meaning this decimal cannot be an out so if you're going to do that you actually have to use a delegate and declare it there so that's another reason why you can't always use func now you may wonder this point before you go on may saying well why do I even have this generate total method here because it seems like most the work is being done here so why not just put all the work here and not even have the method over here that's a valid question and there's a number of reasons I can give I think that the most common one the one that's mostly that I apply here is the fact that typically this method right here will do more than these three things for example it might first loop through the entire list and check to make sure they're all in stock because maybe that was in stock when you put in your cart but may it's not in stock now that you go to checkout and so you need to check that first and we might also check for other things like you can't buy this if this is also in your cart so they can only buy one thing or the others that kind of validation all that goes in here all right it's only this unique to the caller type code where we calculate the discount where you'd want to put that in program C yes another example might be if you're creating an employee account so maybe this was the generate employee and to go through it's going to put their information into the HR system and it's going to you know give them a special access to the different areas they have and all the rest but maybe there's some special things you do for only certain employees or you know certain employees get a different set up a little bit a tweak that's when you use a delegate to pass in those tweaks for just certain cases so while this is really simple the reality is you wouldn't do most if not all your work in a delegate usually you're doing tweaks or modifications and do a little bit of code compared to the overall the method in the delegate and for the most part you're doing you know the rest of your code in this class or you know it's calling other classes but it's not it's not passing all that to the UI I do the UI shouldn't do most of the work and in fact I wouldn't say the UI is necessarily the the layer that used most the delegates I might have a layer you know this demo very might be my base company library that's kinda like the foundation of everything we do but that have another library that calls this library that passes the delegates in you know so this is the the normal shopping cart this is the VIP customer shopping cart processor you know all the different levels where pass is in the different delegates depending on you know what kind of person is checking out or what kind of circumstances you're running into so just kind mention that this is a demo it's not a full-blown application so I want to get the wrong idea of how you use delegates all right so the last one I want to show you before we kind of start taking on a little more the power of these delegates is the action delegate now I'm going to stretch things that's just a little bit because this you wouldn't do it's necessarily normally because it's kind of overloaded what we're doing with delegates I want to show off how action works so it creates a new action delegate again it's just like funk it's just the action returns avoid all right so action we're going to call this mention discount and we'll pass in a string so again we can pass in zero or more of these so do this and if we just do action that'll work as well that's the zero but I want to do action of type string and we'll call this the mention discounting okay this will alert and so I want to have some kind of alert to tell user hey I'm applying the discount now all right so and that's way too close to mention discount we renamed that tell user we are discounting that's really long but that's very descriptive of what it's doing and it doesn't get confused with mentioned discount all right may I should say I mentioned subtotal here let's do that the control dot and rename it alright so now it's mentioned sub no that's a little clearer and now tella tell user we're discounting okay think of this like we want to alert the user in some way so whereas a tell user we're discounting and we're gonna pass in a string which says we are applying your discount it's all going to thing like a log message or an allure of some kind okay again a little bit stretching what we do a delegate because we wouldn't have all three of these delegates in one method I want to show you three different kinds okay so action we pass in a string it returns nothing let's go over to our program CS and here we're going to add a new method and let's call this method private static void alert user string message this is a little more generics the wrong word because we use generic in a very specific way in c-sharp but it's a little more multi-use I guess I could say in its usage so alert user we're going to say console.writeline the message that's it so that's all we're going to do is pass whatever message you've passed through we're gonna write out to the console so alert user I'm come up here to our generate total which is yelling asked now because we need to the third item that third item is our alert user tell user we're discounting okay now if we run this and bring this over here it says the subtotal is $22 and 93 since we're applying your discount and now the total of the cart is twenty one dollars and seventy eight cents so there's that middle one is our our message or alert all right so that's the three kinds of delegate the actual raw kind of standard delegate and then the to upgrade or wrapped delegates which are func and action the difference being that func returns value and action does not returns a void so that's that's delegates in a nutshell but we're not done yet so I'll show off some of the power here and then I'll move over to our wind form UI so the first thing I want to show off let's go down here below the console.writeline which tells us you know calls that method and prints out all three those messages so below that we're actually going to again call the generate total method but this time I want to show you how to do this all in line because remember I said over here that this was a delegate the summit passed in a delegate well we're gonna kind of same thing over here and want to do with ours so you can see how they line up so we know the cart generate total return the decimal it's actually gonna say decimal total equals cart dot generate total okay so you put it into a variable now it's gonna get a little long I'm going to hide that for now but instead of passing in my three methods here instead of pass in new methods that I create on the fly so the first one is a subtotal alert and that's a void just we as pass in our decimal I'm sorry it takes in a decimal all right so we're gonna do is we're opening opening closed parens so a new status is actually there's actually two right now I'm gonna say sub-total alright that's the name of my variable I'm gonna give it and then outside that first parens let's take the outlet so you can see it outside that first set upper ends I'm gonna say equals greater than sign and that's essentially a double arrow or a thick arrow alright and then I'm going to say console.writeline inside here I'll say dollar sign the subtotal for cart - so you identify it's a different cart in the first one the subtotal for cart - is and I'll put my career ace and I'll say sub total which is the variable or passing in here and then : C - and close my curly brace close my double quotes the last thing I need to do is take off my semicolon okay so the reason I did this this way is I'm actually creating in line a full method to pass in it's an anonymous method think of this as shorthand so since it's anonymous we don't need to give it a name for our method because the delegate doesn't care all the delegate cares about is output type and input types in this case as an action so it returns void and it passes in a decimal so we don't you say decimal cuz it already knows that and so we just need to give a name for a parameter so that's our parameter name we wrap it in parens because that's the call for the method so normally a method has open closed parens at the end that's what we're doing here it's just that we're not actually giving the method a name now we say this arrow here that's what whether it's doing a saying okay here's your method and then this one line of code and this is one line there's no semicolon at the end now we can do multiplied I'm gonna show you that a minute but if as single line you just write out whatever code you want and don't press any call at the end if you only have one line of code in this the way we're doing it here okay with just one line so no semicolon just rate out like this so that's saying here's we're passing in your method that's anonymous and here's the actual method body and that's we're also including that paren okay so that's the whole method body so again if you can kind of wrap your mind around the fact that we're just kind of short cutting a whole lot of things all at once that's all this anonymous method that's in line is doing now it's only the first parameter the first delegate which is subtotal alert so let's do the other two so that's why it's yelling me here also saying any a semicolon PN which I'll I'll play it now and now it's going over here because I don't have all three which is cool that's we want I'll put comma I'll go the next lines we have a little more space let's click off there so you can actually not have that intellisense pop-up and it says calculate leveled discount that's our our func which returns a decimal and it passes in those two items so now what we need to do is we need to call that func so we'll pass in the two parameters it needs so the first parameter is our products we call items but I'm gonna cause them a little different products and then the second one is our subtotal and then we'll do again that fat arrow the equals greater then and here I'm going to put my open close curly braces this is we're going to do if you want more than one line of code so this is where we're going to normally we'd run this code right here but in this case I wanted something different than calculate based upon this formula so instead let's create a different formula how out if products dot count is greater than three then we're going to return subtotal times 0.5 M which would be a a 50% discount on trick cart else return just subtotal so you don't get half off unless you have more than three items why is it I'm not sure but at least that generates for us a different calculation than we have in the one down here all right they kind of again illustrates we can pass in different things here and it still works just fine so that's the second one and the third one is the alert user so we after a career ace with comma and I'll put on a new line here again we're going to pass in just the string so the message and I say equals greater than I'll just do an in line again because it's so simple dollar sign where I say alert our cart to alert : message like so and again take off that semicolon that the CW tab tab added for us that's that's snippet so now I've created three anonymous methods and I've done in line which is it's a little messy and if yes if you're passing in three delegates it probably is a little messy but typically you only be doing one delegate for example in our shopping cart model this is one delegate okay so X is our product model and we are passing in and saying okay take the price for each of them all right that's three extension methods so it's a little more complicated but essentially is taking a list and saying for each one grab just the price and that's adding all those prices together and that's the sum so the delegate is saying this is our parameter name or giving it X and then here is the one line of code which is just X dot price we don't need to say return here because that kind of handles it for us but but that's how the delegate is structured is we just return the the value that is the item the property you want to actually sum together okay so in our case here is our three different delegates we have the first one which is our subtotal alerts we have the second one which is a little more complicated but it's our calculate level discount and the third one is just our actual alert the user's let's see how this works so if you run this I bring over here we see the subtotal is $22 93 cents we're applying your discount the total for cart one or cart is 2178 the subtotal for cart two is 2293 and cart to alert is we're applying your discount the only way we're missing is the total for our cart - that's because we never actually printed it out so let's go ahead and do that before I forget about it I also puts a a blank console.writeline before we do the second cart just to kind of separate it will do the same after so dollars whoops intellisense jumped on me dollar sign double quotes the total for cart two is and it's the total : see - and close the double quotes and we're good to go and I'll again put that blank write line at the end so now if we run this it should have separated out into two sections same way it's working 2293 is the subtotal for both we're applying a discount and we're cart to applying the discount and then a total for car the first car is 2178 the Topher cart - is eleven dollars and forty-seven cents because he had four items now just again it can't play with this let's go ahead and take away one item and run this and now notice that the subtotal is the same for both but the total for cart two is 1409 as well because we only had three ends in the cart not four alright so Ella works but we're not done with the demo yet keep saying you know but wait there's more alright and that's the next we're gonna do we're gonna dive into this winform you I would I haven't shown you yet now I've got two buttons here I have message box demo and I have text box demo so the message box demo for each a subtotal the alert and the total we're gonna pop up message box for a text box demo we're going to put the subtotal here we're output the total here and we're going to ignore the alert and that's kind of important now I've got some starter code already in this form so I've got the shopping cart model I have the populate cart dental demo data which I'm calling and I also have the message button click that bring out discounts alert click and the text button click I'm sorry this one right here is just a private void now I've got some starter code in here for this form so how I have the the shopping cart and I have the method called populate cart with demo data which has again the same for demos just kind of show the same thing and then I call that method inside of the constructor for the dashboard form I also have the two buttons click event already created even though they're both blank so now let's look at wiring these things up I'm going to do the same kind of format in that the message box button is going to call the and pass in three methods that are already here as delegates and the textbox demo is gonna have those in line anonymous methods that's gonna pass in so let's first start by creating the three methods around need for our delegate to use so private void let's say we're going to call it print out discount alert and that's the message and we're going to say alright that's gonna be message box dot show and what's gonna put the message in there it's all going to do now right away this shows you the power of delegates again this is not thread safe but don't worry most time you won't need thread safety here but when you do again that async video will cover that guys it's tools aside again but this kind of highlights the power of delegates for this alert I'm doing the message box dot show why if console.writeline doesn't really exist well in the the wind form application it actually kind of works but only if you're running in debugger to alert the user the simplest way is I do a message box dot show well that's great but the console application doesn't have a message box that show and this is where delegates are so powerful because for the console application and say well here's my console.writeline and for the wind forum you can say here's message box that show for a asp.net MVC site I'm totally different all right so that's the print out discount alert that's the first one we're going to do and we're gonna have another one with a subtotal so private void sub total alerts and this passes in the decimal subtotal and what that's going to do is just do a message box dot show I'm gonna do the dollar sign double quotes and here we'll say the subtotal is subtotal : see two looks familiar and again it's the same concept it's just that we're using the message box show instead of console dot write line which is a big difference the last thing we got to do is we have to create that that discount discounting method let's recall this private decimal calculate levelled discount I called this because it's different than our other discount method right we use in our console application we pass in a list of product model and I've already brought in the using statements for this and wired up the the reference that's why it's it's already there so product model call products and the decimal subtotal and now we'll do is we'll say let's calculate this a little differently let's do it again if statement but we'll say products dot count is greater than three and if so where we turn subtotal - let's just say three dollars okay so we will reduce a dollar and you know what let's think it's even simpler we don't have to do a whole lot of calculation here let's it's return subtotal - products dot count all right since there's a count of the products and it's gonna reduce the subtotal by that many dollars now that wouldn't be a wise idea because you know that any ingenious person would be buying 95 cent items because everyone they put in the shopping cart gets on a dollar back and that's obviously not what you're intending here but this is just for demonstration purposes so I wanted something simple so with that being a case now we can come up here to our message box demo and just call our cart dot whoops we're gonna say first our decimal total equals carts dots generate total and Weavin pass in three things first of all our we dimension our subtotal which we do by saying subtotal alerts then we need to pass in our calculation which we call that the calculate level discount and the finally we need to tell the user which is print out discounted alert those three things done or semicolon at the end let's just again hide that from it now we can say message box dot show and let's say a dollar sign the total is and this is total : C to send I call it the end and we're done let's run this and it starred my console application because I did not right-click on my win form UI and say set as startup project alright so open the wrong window I'll work on that in a minute but for right now message box demo we were on this it says a subtotal is $22 93 cents we're applying your discount and the total is $18 and 93 cents this attracted four dollars alright so that's the power of Delegates we're doing a totally different process in a different UI and displaying it differently with different controls that weren't available in the first UI and it still all works let's go back to the dashboard real quick I've got properties and change the startup position to be I believe its center might forget to say that parent I don't think that's it nope that's not it it's Center screen I always get wrong selected properties center screen I believe that's it there we go so now works okay so that's the message box demo let's do the same thing with a text box demo only react all those as in line methods those anonymous methods all right so here's our event code here so now let's wire this up and we'll do it right as simply when I kind of go overboard with our complex code but we'll say decimal total equals cart generate total and the first one is our subtotal which is will say subtotal again equals greater than and this is going to be subtotal textbox dot txt equals and I'll say dollar sign double quotes in right away to clear braces subtotal : C 2 so they'll put the subtotal in that text boxes text value all right Anna will format for money next up with the next line we have our calculate discounted total so I will say products comma and the next one will be subtotal equals greater than and we'll say subtotal minus products dot count so it's just taking again it's the same same functions down here masion we'll do this times two all right so we'll kind of double your your bang for your buck here all right so that way it's a little different you just be clear that's a different calculation all right so that's all we're gonna do for that when we're not going to do anything fancy there so it's just again one line no Stan I call at the end no return statement just here's the value that hole that it gets returned and the last one is our message and that's kind of our alert but I don't want to do anything this I don't want to alert the user things happening so I pass in open closed curly brace and that essentially is going to run that method which has nothing inside of it Anthony done so that's how you can kind of bypass something you don't want to deal with in this case I don't want to deal with that message I just want to pass in an empty function an empty method and say run that I don't really care all right so now for a text box down I click this and I hit this one I forgot to fill in this one so let's go ahead and do that so down here I should say that the the total text box dot text equals dollar sign double quotes oops double quotes and then clear braces and we'll say total : C 2 and that's it so I call it the end so now if we run this in theory everything should work and there you go there's your subtotal and your total by just clicking the button message box still works and it gets a different total than our total over here all right so that's kind of power of Delegates you can use them in different applications and have them do different things and your base library doesn't have a change at all so if you have a little bit of logic somewhere that the change is often or that might change it might be a good place to use a delegate now one of the areas you use delegates a lot is events okay so if we actually look back at this code here how does that method get called well it's actually wired up as a delegate all right so if we go over to our solution we open up the dashboards and go to dashboard designer dot CS and we expand this code here we scroll down we'll find the well here's a message box demo and here's a text box demo the click event we're adding a new event handler which if you notice is a delegate and to say okay here is a delegate that's the method name the method name is textbox demo button underscore click which textbox demo button underscore click so it's just passing this method in and saying call this whenever the event gets fired so that's how we're kind of elevating events just a little bit with a little bit different flavor with events I'm sorry elevating delegates with events but the concept is still a saint we're passing in this method to be called elsewhere where elsewhere doesn't really matter now right now in this form is being called in the same form but they don't have to be in fact where it's being called on this for is not actually in this code here it's not in here anywhere it's being wired up online 57 here but the actual call to this method or all the methods in the event handler for the click event they're not being called here it's actually through inheritance so if you look at form here form actually inherits from dashboard now it's not this is not a form event so it's not action being call from form its actually being called from button because it's actually a button event so I feel a little confusion there but if it's a form event it'd be called from the base form class in this case the button is actually a class if we go here and look please expand this out actually tells you the its system that windows not formed up button which is a class and this is an instance of that class well that class has some events on and one of those events is the click event and so we're passing our method here this method right here right there we're passing that method into the base class which is the same for everybody so Microsoft designed a class that can be used by me and can be used by you and can be used by millions of people around the world and all of us do it differently also use it differently and that's okay it's flexible that way and that's the power of delegates so what we've seen in this video so far is that delegates are really simple they're just methods that are passing in and there's a couple different ways to declare them one is to actually explicitly put the contract in a place that everyone can see it and this contract right here is the delegate another way is to declare in line as a func which returns a value or an action which does not all right and either way what we do then is we can call it from somewhere else either our console application like we do here or from our wind form application like we're doing here now we can also pass in a full method like we're doing with these methods down here or we can pass in in-line methods like we're doing here and here and here alright so either way works now the one question that may have popped up that maybe kind of rattle around your brain I so make sure that we've I've been clear on it is that this method this this one right here actually returns of value so where is that return value now I use some that kind of tripped you up a little bit you know so in this case down here we declare explicitly and it's the calculate leveled discount and returns a decimal but when we call it we don't capture that return anywhere and that's because it doesn't return it to the wind form UI or the console UI instead if we look at the calculate discounted total notice that that's where the return is coming in and we're right in line returning that value so I could be more explicit and say decimal total equals and then return total okay I'd be a little more explicit so that method has a return value which wherever we call the method that's what gets the returned value so just kind of clear that up in case that was a question hopefully that cleared up some things about delegates and how they're declared and how they work like I said it it's not hard stuff I know it looks a little intimidating and if it's still a little in today that's okay take your time but when you get right down to it you're just passing a method around and letting the person you're passing it to actually call the method instead of you calling it so that's all you're really doing with delegates I hope this has been helpful don't forget down in the description you'll see the link to get the source code at this point as well as the starter source code so go to my blog for that that's in the description down below and also at the end of this video I'm going to include some other videos that might be helpful and I want to check those out as well alright thanks for watching and that's always I am Tim quarry [Music] you [Music]
Info
Channel: IAmTimCorey
Views: 173,777
Rating: 4.8976955 out of 5
Keywords: .net, C#, Visual Studio, code, programming, tutorial, training, how to, tim corey, C# training, C# tutorial, delegates in c#, c#.net tutorial, c# delegates, action, func, func in C#, action in C#, c# delegates explained, c# delegates events and lambdas, c# delegates example, c# delegate vs event, lambdas, anonymous methods, c# anonymous methods
Id: R8Blt5c-Vi4
Channel Id: undefined
Length: 69min 11sec (4151 seconds)
Published: Mon May 28 2018
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.