Advanced C#: Lesson 4 - Delegates Events and Lambda expressions

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
hey guys welcome to the fourth lesson on advanced c-sharp programming today we talking about delegates events and lambda expressions we're gonna talk about what delegates are how do we use them which one both events and how do delegates work with them and then we'll talk about lambda expressions in what are the benefits of land expressions over anonymous methods and and things like that so let's get started so the first question is what is a delegate in the most simple definition of this which I really think even though it's very simple I really think that this helps people to understand what a delegate is a delegate is simply an object that can hold a reference to a function or it's some kind of object that points to a function right if we have a class and we instantiate and we have an object with an instance of a class that object is pointing to other memory all right we have that picture but it's pointing to a block of memory that that object will use where a delegate is very similar to that where is a delegate is an object that points to a function rather just a function so I could have an object that's pointing to let's say main and if I use that delegate it's gonna be interacting with main so I can invoke my delegate and whatever my delegate is pointing to it will it will execute that function and things like that and we'll get into this what I'm talking about so yeah the most basic definition of a delegate is that it's a object that can hold a reference or refer to a method so when we go to set up our first elegant there's a couple things I need to note about the actual syntax of it and what is the delegate doing what does it require so um so when we when we define a delegate we're making a signature for it and we're pretty much saying that any function that that has the same signature or has the same outline of this delegate is allowed to be used with this delegate so that means that any method that agrees with the signature and the return types um the delegate can hold or point to so when we go to define a delegate we need to define the return type and the parameters of what all functions must have in order to work with this delegate so let's go ahead and do this and we're gonna just mess around with some basic examples and they will get into more complex ones as we go because this video is probably gonna be pretty long who's looking at how much things how many things I need to go over so let's just make a delegate so the syntax for it is the the delegate keyword followed by the return type of the delegate so we're gonna say in this case we will use a void then the name of a delegate so we'll say I don't know my del this is just a test and then it's the parameter so I'm gonna say it's gonna take in a string and all the and yeah that's it okay so pretty much what we did by defining this is we're saying that any function that wants to be used with this delegate must have a parameter list of one string and a return type of void if any function matches this that we can use it with our delegates so now we have our delegate got the delegate let's go ahead and make a function that works with our delegates so we'll define it over here and we're gonna mark it static because main is static so we're going to say static the function requires a return type of void because that's what our delegate specifies right here so then we'll name our function we'll say test function and then a has to have one string parameter so text will make this function at the text that comes into this we're just going to display into the console so let's council outright line text so that's our test function so now we have that now we can create our delegate remember our delegate points to a function and now this this function signature and return type matches our delegates so inside of main now to create our delegate we're going to say my del and we'll say del equals a new my del so we're allocating the new delegate and as you can see inside the parameters it's saying our target must be a function it has a return type a void in a string parameter which test function does so I can just pass text test function right in like that so now my del is pointing to test function now that it is Ori I mean del now that it is now I can use del as if it is test function because it's pointing to it so I can say del and I could pass in you know hello world so now del what's gonna happen is this string hello world could surpass its my delegate and my delegate is gonna call all of its function in its invocation list which is only one function right now I'll get into that more so it will pass to test function and then it will perform this functions if we go ahead and run this code now we see it says hello world so once again what's happening is we have a delegate and our delegate it's pointing to test function once we pass into because it's pointing we can treat del as if it is the function so I'm using del and you can see when I do del and do that the string it actually says string s so it's looking for a function with a string s so that's where this works so that's why I could pass and hello world so um since version 2.0 of c-sharp there's a simpler way to actually create a delegate and and assign things and do all that stuff so it's called the method group conversion and allows us to instead of calling this new my Dell and all these things if we leave it out and we just say my Dell Dell equals test function like this the compiler will automatically inject the call to new and all the necessary things so we don't actually have to supply so this is just the shorthand and this is what I'll use from now on I'm not gonna specify the new and in the constructor and everything I'm not gonna explicitly invoke the delegates constructor so this is I'm going to use the method group conversion this syntax it's just a simpler syntax for interacting with delegates so another feature of delegates is this concept of multi casting and multi casting allows us to pretty much create an invocation list meaning that our delegate can point to a not just one function but rather it could point to many functions and it has a list in its invocation list of what functions it should call and in what order and we can build that invocation list with using familiar operators you can use the plus plus equal and minus minus equal to respectively add and remove functions from our invocation list so for example if I wanted to add test function in again I could go del plus equal test function and that will add that to my invocation list so now delegate is pointing to two it's pointing to two test functions it's pointing into this twice and you can see if I cut this to references you can see where that's happening so and now if I run it as you would assume we get hello world twice now so we built-in behind the scenes our delegate has this invocation list and we just added to it by using the plus equal we can remove from it and etc so I just added to my invocation list like that one thing to note that this is pretty important if you have an invocation list and say it has five functions if those functions have return types that are not void meaning they return some kind of value then what would happen in that that situation and what happens is because if I call these and they all had return types you know what return type would the whole delegate take and what happens is the value that is returned by the last method in the invocation list becomes the return type of the entire delegate so whatever function is the last one will become will become the return type of everything so I'll demonstrate this right now so the first thing I'm going to do is I'm going to modify my delegate to return a string instead of void and it's gonna take in no parameters like that so we're obviously with the change this so let's modify the first text test function to do string and no parameter list and all I'm gonna do is that the first test function is gonna return hello world and I think another function and the second test function - it's gonna return I don't know by world so test function says hello world and test for chooses by world so now if we start our delegate and we say my del test l equals test function the state will start out with that then we'll say test del plus equal test function - so now our now we're putting - both of them so they both have a return type so if I say string results equals test del like this what is rubs up what is results gonna hold because you know both of them have return type so what one will actually use so if I go ahead and display results we'll get our answer and as you can see the return is by world and that is because I said before if you have an invocation list of return types the last function that returns the value is the return type for the entire delegate so there that's how that works just on a quick note again if you see I just want you guys to really visually and and mentally understand that if my delegate is different let's say my delegate has a string parameter now you'll see that all these things error because the functions that they're pointing to don't have string parameters what if I go like this and I say string X here boom test function will now go away if I do the same thing here now that error will go away and the last one is because I'm not supplying a word so I can do that now that will go away so that just shows you that the delegate must match the functions that are being pointed to so now we'll get errors again but then the errors will go away if I change my delegate so yeah I just want you to really understand that a delegate a delegate points to a function and B the function that it's pointing to much Matt must match the delegates requirements okay so now that you understand that now let's confuse you so I just told you that the functions that the delegate points you must match the delegates requirements exactly but however that is not entirely all true and I'm not gonna go into this in too much detail rather just quickly explain it so there's two concept called covariance and contravariance and pretty much what they do is they bend the rules of the delegate requirements and it's really only because the concepts of inheritance and how that works so so there's pretty much just two rules when we're using inheritance and delegates so the first one is Co variance and covariance allows a method to be assigned to a delegate when the methods return type is a class that derived from the class specified by the return type of the delegate so I bet a bunch of guys just want what so let me say that one more time and explain it so covariance allows a method to be assigned to a delegate when the methods return type so we're in this kind of situation we're talking about this function so when this methods return type is 8 so string is our example right here when that is a class that is derived from the the delegates return type so if this try to show you an example real fast yeah let me really quickly I'm gonna build two classes down here let's go class animal no I'm not gonna give any definition and then class dog which is in animal so these are two classes so let's do the rule of covariance really quickly so let's say this had a return type of animal and so let's take old this always work with one function okay so let's say our delegate had a return type of animal the covariance I'll read one more time covariance allows a method to be assigned to a delegate when the methods return type is a class derived from the class specified by the return type of the delegate so that means that that allows us that since the return type of this elegant is animal that means that the return type of a function that is pointing or getting pointed to by the delegate can be one that is derived from it so if I put dog here the error will go away I always see that's erroring now but as you can see this error run away and that's the that's what we're talking about right here so that's the rule you could point to a function from a delegate if the dello if that function return type is derived from the return type of the delegate okay so hopefully you guys aren't too confused with this so this is just you know the main rule applies is that there they have to match completely but this is inheritance you know with the relationships of heritance and is that is a relationship allows these rules to be used so that's the tricky part with that but if you understand inheritance you would understand this so that's covariance now contravariance contravariance allows a method to be assigned to a delegate when the methods parameter type is a base class of the class specified by the delegates declaration so this rule works like this let's say we had let's make this void again well let's say this my del required a dog did say for example we could use test functions note this air right here we can use test function if the parameter of this function is a base class of the parameter that of the delegate so if I say animal a that error goes away so as you can see those are the two the two rules covariance and contravariance covariance is working with the return types and contravariance is working with the the parameters but yet if if you ever came into a situation when you're working with these two things do you a quick Google search and you don't have to remember this I mean it's not really remember the can you just remember that there is covariance and contravariance out there somewhere now let me before I continue on me really quickly say that this video is definitely for people this is an advanced t-strap video if you're learning c-sharp for the first time and you went through the fundamental videos and you and you think you're ready for this and this is an advanced video this is really hard to understand if you are not at the right level right if you're if you're trying to get at this too early of a programmer you're gonna have a really hard time so I just want to say that this is really advanced and if you're not ready if you see this is too hard for you to understand go do other things learn programming more and come back you know once you think you're ready all right so with that out of the way let's quickly before we move on to this concept of anonymous functions you know why do we why are delegates even here you know I I showed you and I explained a delegate points to a function so a delegate is an object that holds a reference to a function but why you know why would I ever want to use a delegate you know everything that dela can do I can kind of work around it can't I you know if I was learning it that's what I would say and there's two you know pretty good reasons why we would use this the first reason is that delegates completely interact and work with this concept of events which we'll get to we'll get to an event that's the last thing we'll talk about so just on a sign I'll just remember that back and ahead that and you'll see the importance of it then but delegates and events work hand to hand so that's one benefit of delegates and the second benefit of delegates is that delegates give our programs a way to execute methods at runtime without having to know exactly what the methods are at compile time so pretty much what that saying is is a delegate because we can control with thing we can control the program with on program flow control you know at compile time we don't necessarily know what functions gonna be stored in that delegate at runtime we'll know but that's the bit that's the power of delegates because it's a it's a variable pretty much it's a variable that's pointing to a function that can change right we can we can add things to the invocation list we can remove things we have just pointing out one thing so at runtime that's when we really know what functions were pointing at whereas at compile time we don't know wait so that's the basics of delegates the next thing the vernest are talking about is this concept of anonymous functions now third types of anonymous functions that we'll get into the first is anonymous methods and then lambda expressions also about them both but mostly I'm gonna spend most of time on lands expressions because lambda expressions were kind of created to replace anonymous methods and they're more simplified and it's a shorthand for anonymous methods pretty much but overall the whole concept of anonymous functions what are they okay so there are gonna be times oftenly that when you're working with delegates you're gonna be creating functions that are simply only used and the only purpose of that function is to be used with the delegate meaning that you know that function will never be called on its own you're never gonna make an explicit call to that function the the sole purpose of the funk of that function is to be used with the delegate and when you have times like that that is where we use anonymous functions so anonymous functions are simply inline functions they're pretty much functions on the go I like to think them you pretty much wherever you're gonna be using the anonymous function is that you create the whole function right in that specific you know instance we're ever gonna be using that anonymous function it's created right there and it could be inline it could be within another function and it's anonymous because there's no name attached to it you know you don't associate the function with a name an anonymous function has no name and the point of that is the function is only used with with whatever it's being used with right there and that whatever is using it that can only use it right there's no name to it so that we can't go back and make a call to it because it's anonymous we don't know where it is we don't know the name of it now anonymous functions work well with delegates because delegates point to functions and just because we're I mean if you think about this logically if you would non Miss function how are we gonna keep track of that anonymous function and a delegate points to function so pretty much my delegates point into my function and now I can treat now I can follow that anonymous function and interact with that anonymous function through my delegate because my delegate has access to it pretty much my delegate only knows where that anonymous function is and yeah so and not once again an anonymous function to sum it up is a function that has no name really the basic definition it's a function with no name so um like I said there are two types of anonymous functions the first ones anonymous methods and the second one is lambda expressions anonymous methods like I said are kind of old and no one really uses them besides like old legacy code so lambda expressions kind of replace that because it's easier and it's a shorthand for anonymous methods but I'm gonna show you one example of an anonymous method just so you can see what it looks like and what it used to look like and it's good to know because like I said some legacy code still uses it so if you saw it you need to know what an anonymous method is so we'll first you an anonymous method so let's do that let me clean this up we'll keep our delegates but we'll just do that so our delegate we're gonna call count it and our delegate our delegate is simply I'm just gonna make our delegate point to a function that counts from like one to five or something and display to the console using anonymous methods so you know I mean if we will first start off with building the explicit function you know that whole function will start with that and then I'll show you how to convert the into anonymous method and then a lambda expression so to start let's build a function that supply that works with this delegate so static void test function so that's our function and all I said also gonna do is we'll do a simple like loop or something is less than 5 I plus plus console dot write line let's do some like that so it just displays some output and then we'll make count it test del equals test function it's point it's pointing to our function and then I'll call test out and let's see the output 0 1 2 3 & 4 so that's all right output that we want now let's do the same thing and convert it to an anonymous method so we'll leave this here for reference so we have our delegate right and we don't want explicitly create it like I said because all those rules before you know if it's only gonna be used with this delegate why would we make an explicit function we don't need that so to do an anonymous method it looks like this count it test out and we need to point it to a function so we're gonna point it to an anonymous method so it goes like this you say delegate you use the key or delegate here you create the body of the function and then inside of it inside of it this is what it looks like this is annoying okay so this is what our delegate looks like now so if we run this Austria we look what if the what's the problem I didn't make a call to the function so let's go test Dell down here now I'm calling my delegate and let's see what happens as you can see the code gets executed so what's happening is we're saying delegate so this is the note that were to the compiler that were specifying an anonymous method in here so inside of our body of our delegate this is the body of the function this is essentially this right here is essentially this test function down here with no name then that's the benefit of anonymous method so it's in line it's inside of this method we built it and it could only be used with this test I'll because the test cell is pointing to it and there's no name attached to it so we can't call it just call delegate really that's just a keyword so this is our body of it and then when we call test L that it uses the body of this anonymous method all right so really quickly um let's say what if our delegate said oh you know my function now requires an integer you know how do we work with this John you can see we're getting an error and the reason is because our delegates our function doesn't have a parameter of integer so where do we add that parameter with anonymous methods and it gets added right after Delegates so I could say int X here I'll just display the X whatever is passed in so now that I have that so this is where my parameters go for my function so this is my nonnamous method now the parameter list goes here and there's no name obviously and to execute this now let's just pass in like 100 in the test delegate because our test delegate is using this delegate right here so it says oh I need an integer when I run it now a hundred gets passed into the anonymous method through the delegates parameter list like that and the last thing with anonymous methods is what if our function has a return type of int you know how do we interact with this now and this is the same rule applies so let's make our function add all these numbers together and say int total equals total plus equal X we won't display it but then we'll just return our total so it works just like another function does the error goes away and now I can say you know in total equals oops say and now if I display that overall total this is what I get the 500 which is correct so that's how you use return types parameters and everything with anonymous method so that's the basics of anonymous methods you know the most important thing to really get out of this is you know why what what are what are non miss functions and why do we use them and we use them because of you know when we want to interact with delegates and there's no reason to call it we don't want a name for it and things like that we're pretty much creating functions on the fly I like to think of it that way when I use them you're creating a function on the fly just to be used for a sole one sole purpose so that's a non anonymous methods so now we're going to switch to lambda expressions because lambda expressions were created to no I don't want to see replace anonymous methods but lambda expressions are shorthand for it in May and they're just a little bit quicker and easier to use all right so what is lambda lambda expression we pretty much went over a lambda expression is essentially or not it's a non Miss function a lambda expression is an anonymous function um it's just handle a little bit differently than anonymous methods are so two Creole and expression we use the lambda operator which is the equal signs and then the greater sign so that it makes kind of like an arrow and we can refer to this as the as it logically saying you know we can verbalize it as goes to or becomes so it works the same exact way so um let's first set up our delegate so let's say we're creating a delegate count it test del equals and then what does it equal so this is where we put in non rest methods we could plug in an anonymous method we could plug in an function or you plug it in a lambda expression so when we work with lambda expressions there's two types of lambda expressions that we should be familiar with the first one is expression lambdas and the second one is statement lambdas expression lambdas is pretty much when you have one statement inside of it it's one expression um that's considered in an expression lambda a statement lambda is when you have a block where you create that block of code and then you have return demons and things like that what we'll get to so the first thing we're going to do is an expression lambda so if we have our function return type of int and takes in an int how do we do this with lands expressions so there's a couple ways we could do this the first ways I'm going to show you it's by explicitly up explicitly saying everything to make it more clear this is the way I like to do it so we're gonna create on watch the first thing is on the left hand side the left hand side of a lambda expression is the parameter list and the right hand side is an implementation or the body of it so on the left hand side we're just specify the parameter so our first parameter is int X that's it then it's our lambda operator or goes to and then this is going to be a statement lambda expression lambda we're not gonna have a body it's just one statement so what we're gonna do is we're gonna say what should we do we'll take whatever is passed in and five and return it so we'll say X plus five and that's it so what happens here let's run it and then I'll explain it so if I go resent results Bickle's tests out I'll put in five then I'll display results and run it what do we get we get a ten so what is what's going on here so this right here this is our expression lambda or a lambda expression more generally and what's happening is on the left hand side of our lambda operator this is our parameter list so our function requires in a one parameter of int so we specify that parameter in our lambda expression we then have goes to and then this is the the expression part we only have one statement inside of it now our delegate has a return type of an integer meaning our function must return an integer so how do we do it there's no return statement here and that's because if we're working with expression lambdas which is only one statement by default it automatically if there's a return type required it will return the value of that expression so our expression is X plus five and it will over it will automatically by default return that to make the delegate happy because it needs that integer return type so that's what it'll do it will do that return right there automatically so that's how we're getting the ten ik it gets five gets passed in five plus five is ten and then that gets returned into the result and then we display result so that's the most important thing to remember with expression Lam does is that the return statement is in its inferred really because of the return type here now talking about inferring things the compiler to also infer other things right because it inferred this return type of integer well then I can also return the and for the parameter because it has the delegate to go from count in is a delegate which requires an integer parameter so essentially we don't even have to specify that we could just say X although I like to specify it because it makes it easier to read you don't have to I could remove these and say X goes to X plus five and this is really the beauty of lambda expressions um it's so simple like this right here is an entire function call if I were to remake that function how what would it look like it would be static static int I don't know my function here its X return X plus five so this entire thing right here is this one statement right here so that's really the power of an on of Lam's expressions that I can rewrite this entire function like this all this one line of code right there that's these two are logically equivalent that in that are logically equivalent so yeah but still like I said I like to actually specify my types just because I know it feel not that much code but it makes it a lot easier to read so that is an expression lambda the next one staying with lambda expressions is statement lambdas and statement lambdas are essentially the same thing it's just it allows us to add more code into it mates allows us to have a body we can add loops we could add if statements we get anything we want but then then also you know by adding those extra things it removes the ability to infer the return type and infer the return statement so then in those kind of things we have to explicitly write um so it's the return statement so it's making it into a statement lando we just simply add the body to our to our delegate so why scissor this is a yeah so it says not all code pets are returning value so we need our return type now because it can't implicitly derive it so in this we could be like you know well all that really do is return X plus five that's it but yeah so this is a statement lambda pretty much it allows us to blow it up and we can we can have multiple statements now by adding the block of code in but like I said by doing this we lose the ability to infer the return type so now we have to actually specify explicitly the return type with the return statement but the benefit is we can do fun things I can make a loop so I can make a loop and and do things in here like console dot write line I don't know hi so when I call it now at my results you know my function is displaying hi now so we get that benefit of being able to call multiple statements if we use statement of statement lambdas but like I said we lose that ability to infer things we lose that ability to keep it as compact as possible so the only time you really really gonna be using statement lambdas is if you have multiple lines of code if you're just doing this return there's no point I can convert this right back into my X plus five like that and that's it so that's expression lambdas and statement lambdas so now that we've got through all this we got through delegates we got through anonymous methods I got through lambda expressions these are all basics right we go into a lot more details with all these things even though it's an advanced video it's still a basic I explain things in the basic way so everyone can understand it and once you understand it then you can take to the next level and use it more advanced so the ultimate the ultimat you know thing with understanding it's understanding it in the most simplified form and that's you know that's my biggest concern with most programming books is that when they're explaining complex you knew things to new beginners and people are learning new topics they explained them didn't they go into detail like all the advanced things that you can do with it you know that's good and bad at the same time I think it's more important to understand something in the most simplified form and then once you understand it then you go to the next level that's my philosophy and all my videos I followed this all the time I always do it the most simplified way all right so now once again we got through delegates anonymous methods lambda expressions and now the bulk of it you know why we're using all these things comes down to this concept of events what is an event so events in the most simplified definition that I can really supply for an an event an event is a events are simply a programming notification system just like our phones you know our phones our smart phones have notifications systems in it and essentially the events are essentially notification systems an event allows us to let's say hypothetically let's say we're building a class and I implemented an event for some kind of action let's say we got a message right let's say our class was dealing with messages in our class got a message you know if we supply it implements this concept of events we can use this event to notify and make notifications to people who really care about them so if there are other classes and other things interacting with this class that deals with messages those classes can subscribe to my event and if I get a message I'll notify them and then they can use that information with however they want to use it so events are ways that we can notify other objects when us up when a specific action has occurred so that's simply I mean the basics weighed on I think the easiest way to understand it at least you know events allow us to notify other objects that some kind of action or event has occurred so the easiest way to see this is with examples so how should I do this okay I'm gonna make a class I'm gonna put it all in line so or in the same file so it's just easier to read it and understand and we can all see it at once some create another class down here in the creek last called person and my class person is going to have let's see it will have a private int you know that's not realistic a private int called cash so our our okay our person has a wallet essentially and it has some cash in it we're going to make a function say void add cash that adds cash to our wallet essentially so in amount and it's simply just gonna go cash plus equal amount so our add cash function simply adds to our cash actually let's make this a little bit more realistic actually um yeah I'm gonna convert this into a property so let's go public in cash home make this real this is just a property and I'm gonna use the property here when I add cash like that alright so I create on my private data and I created a public a public property and I'm gonna use this with my event system and you'll see what I mean by that so my goal what I wanted to I'm the developer of this program I want to create an event that will notify people who care about this person when he sa receives $100 or over a hundred dollars so once he hit that $100 amount or over to the matter as long as at least a hundred I'll notify everyone that oh this guy has a hundred dollars so that's my goal in this little program so how do we set this up now what I'm about to show you is I'm gonna save this version and then as we get further into the lesson then I'm gonna show you that there's other ways to accomplish this and I'll show you the easier ways but we're first gonna start with the most basic type of how to do this so the first step is we need a delegate because events work with Elias we need a delegate because this how it works when someone who is interested let's say someone wants to know when he reaches $100 when that person's interested it may subscribe to my event and when they subscribe to my event they have to implement an event handler and that event handler is what gets executed when I notify them so when I say okay notify all my subscribers they're all my subscribers event handlers are what get out that are or what gets executed and that when they get executed that notifies them that the event was fired that event handler that they implement must follow the guy of the delegate that the event uses so now you can see that it's all coming together so the first step is we need a delegate so we're gonna say delegates and our event handler what would our event handler do will say void my event handler and no parameters it's just a basic void no parameters delegate now that we have our delegate now we need our event let's make this now we need our event so let's go public event the syntax is public event then our delegate that our subscribers event handlers must use that's gonna be my event handler that's our delegate and then our event so we'll call it some event or actually we'll call its cash event so we have our delegate and our event now that we have that now we need to before we implement the handler in our subscribers we need to you know when this action happens when our cash is greater than a hundred then we're going to notify our subscriber so how do we do that well we do that by first we need to do a check you know if our cash is greater than equal to $100 so we have $100 or more we're gonna let our sub scribers know so we're gonna notify our subscribers how do we do that the first thing we need to do is we need to call our event if we call our events that calls their delegate and calls all the event handlers that are subscribed and are in our delegates invocation list so to do this I first want to do with this check I'm gonna say if cash event is cash event is not equal to null and the reason why I'm checking that it's not equal to know is if there are no subscribers I mean there's no one that's wants to know when this event happens then the event would be set to null so by checking that it's not equal to null is I'm checking to make sure that there are some subscribers so if there are any subscribers then we'll fire the event so we did our check now how do we fire the events now we're gonna call we're simply just do cash event and call it this fires the event right here so okay this is our function our add cash function makes our cash increase if it goes over a hundred and fires the event and lets all subscribers know so this is our person class now instead of main let's implement this so let's first start off by saying person P equals new person we got we got our person right there so I'm this other person and I want to I want to be notified when this person this specific person gains $100 or more so to do this I'm going to subscribe to his cash event do you see cash event with the little lightning bolt so I want to subscribe to this cash event so how do I do that I go cash offense and now I want to subscribe to it and I want to create my own event handler so we're gonna use the same multicast syntax I mean you saw what the delegates will say plus equals and as you can see um it's giving us a default we can just hit tab twice and that will create our or event handler for us we don't have to do this but I'm gonna do it anyway it makes it easier so I'm a tab tab and what we get is we get our function and our I mean yeah our function and and what we're pointing to so okay let's just break this down a little bit so we can understand so our delegate has a return type of void and no parameters and that's attached to the event so that's what we're getting this information from right here void no parameters this function was created to because it has to work with the requirements of the delegate so this function was recreated to work with the requirements of the delegate and then our delegate essentially is where now we added this function right here to the invocation list of this delegate which is this even though this is an event behind the scenes we're using the delegates power to hold references to functions so right there that's how we have the reference to this function so inside of here I'm just gonna say consult right line person has gained $100 like that so if I were to run this program right now nothing would happen because the event wouldn't get fired because our person doesn't have $100 so let's start off by saying okay P dot add cash that say $50 run it there's an error what's the air oh okay all right let's run it do you still have an error what what what is the error that's annoying okay okay sorry about that okay so where were we so let's go ahead and run this as you can see we don't get any output because he doesn't have $100 yet if I do this again however so I added $50 and now I'm adding $50 again that's a hundred bucks so essentially we know that it was $100 we're gonna fire our event and let all our subscribers know we're a subscriber this is our subscriber right here this makes us a sub scribe this line right here so now our function that we subscribed with will be executed because it has $100 let's run that as you can see the person has gained $100 so yeah and that's how it works so let's debug this and step through it so you can see what actually is happening um where should we do this I guess we really just look at the this cache property so let's run this okay so the first time we get into cache get to it return can - okay step wait a second let's try this again let's go ahead let's put a breakpoint inside the set function that's why we're okay there we are so this is the first time we're adding cash when we come in and we do this check so cash is now equal to $50 that's what we did the first call is cash it's for the greater than it goes 100 no so we don't ever enter in and let our subscribers know okay so we come out and cash is called again we come in yes we get into our cash this time now look cash is a hundred dollars it's a hundred greater than equal 100 yes we step it so if cash event is not not equal to null as you can see I wonder if you can see this okay um I don't know so boom arm overall it cash event is not equal to no as you can see we definitely it has some data inside of it it's not equal to no and that means that we have a subscriber so and I'll show you what what happens if we don't so we have a subscribers let's notify them so we call cash event and as you can see my function right here is getting called because I subscribed with that function so then there that's where the statement gets executed let's run this again but this time let's not subscribe to the event and what does it look like this time so we come in the first time it's not $50.00 so the second time so now we're at $100 when we enter when we enter it so we get into here and we do this check if cash event is not equal to no look cash event is no because there's no subscribers as you can see because there's no subscribers cash event is equal to null because we don't have that line of code so that's a difference if we have subscribers and a cash event is not equal to null so because it was nobody don't notify anyone and we move on with their life nothing gets notified there's no output so this is the basic idea behind events events allow objects to notify other objects when a specific action has occurred so in this case we want to build a program that if their cash goes over $100 we want to notify all the subscribers you subscribe by adding your function to the invocation list of the delegate supply in the event we do that by creating a function that meets the requirements of the delegate and then we just add by using the multicast syntax to the cash event and now it allows us to subscribe to it so when the class says ok notify all my subscribers this is what happens okay see that's the basics with events now the same rules apply with delegates right I could have there could be multiple people who want to subscribe for this event also so I could have another function subscribe to this same exact event of this same exact instance so you can use multi casting and and do a bunch of different calls so you have as many people as you want subscribe to this event okay now but also another thing you are talking about anonymous methods and lambda expressions those obviously still work with this because our delegate is still behind the scenes in this event so we can use all the same things with that so let's say if I wanted to change this around instead of actually making this explicit function let's say I had cash event plus equal and what our delegate our delegate is void return type no parameters so how do we do that no pram I guess the best way to do that is going like this so we're saying nothing no parameters goes to this our lambda expression and we're gonna do console dot write line person has a hundred bucks so does this lambda expression match our events delegate does it so we have no parameters no print on no parameters and no return type yeah yeah it says a return void right yeah nothing is being returned so we match the return type of void also so this is our land expression we could do this as well if we run it we still get the person has a hundred bucks the same thing happens we come in actually I'll show you this real quickly if you don't know about the debugger there's some cool things we could do with this I'm gonna change the hit count to break one hit count is equal to two so if it's the second time being int I wanna do the first one anymore so if I run this now when we enter it we have cash is equal to let's go to the next line cash is equal to $100 this is the second time we got into it so one the when the cash event is called now it goes look it jumps to the function that subscribed to the dela subscribe to the events this is our event handler and it jumps to the lambda expression execute that line of code so the same thing happens here the same thing happens except we're using lambs expressions so just note events can use a Thomas method lambda expressions you can use its own functions and that thing that you're pointing it to you is that when I'll event handler so the last thing I'm going to be talking about in this lesson me chattering there's really two things kind of similar the first thing is guidelines dotnet event guidelines now these guidelines do not have to be followed right because you know the thing that you do are for yourself but dotnet follows these guidelines and I'll show you what happened they even follow them and they follow them because they were trying to make a standard they were trying to make a standard for their languages but you don't have to follow it but the guidelines with events are pretty basic and I'll show you how they work the first guideline is well the main guideline is that all events or essentially the delegates or event handlers must have two parameters every single one must have two parameters that's what they want the first parameter should be a reference to the object that generated the event so in this case the first parameter in my event handler should be a reference from this person saying that a person is the one or this person more specifically is the one that that called the event and I'll show you how we can follow the standards here in a second the second standard or the parameter is that the second parameter should be of type event args and that should contain any information that should be passed forward should be contained inside of event args now the actual event args class isn't used that way we should work instructed to create our own event hand or our own event arguments that derives from event arts and that can have some information you know the details aren't that important with this rather than just know that these are the guidelines that they follow so I guess I'm going to show you that the first thing I want to show you is the guidelines that they follow and where they and it's actually sure that they actually do follow them so I'm gonna create a new project actually yeah let's go file new project I'm going to create a windows form application project and I'm going to put it onto my desktop my desktop that's gonna call whatever hit okay so what I want to show you that is at their events they follow the same guidelines for their events if I go ahead and put on a button now if you don't know this don't worry I just wanna show this is a button and as you can see there's a this lightning bolt which stands for events buttons have all these events and they work the same way that how we just use them before if I double-click on it that will create an event handler for the so it created an event handler for the button being clicked and as you can see the standards that dotnet placed for the event guidelines is is being used here we had the object sender and the event art so the standard once again was that the first reference the first parameter be a reference to an object that is that generated the event so whatever generated the event that's what refers to it here and the second is the event args which contains any information that contains any information that it should be needed by the event handlers or the subscribers in this case I'm the subscriber of this button click I subscribe to their button click and I am yeah I wonder if I get to the code-behind let's see if I go to definition here oh there it is look at this so this is cool stuff for behind the scenes this kind of behind seats this is the the the form one designer class and this is what it is actually actually I don't know if this is actually calling it but you can see that um this syntax right here this is where we're actually registering for or subscribing this is our subscription right here and we're subscribing to the click event right here if you as you can see if I go this button one click click is that lightning bolt and when we create our own function arming our own delegates we got that same lightning bolt effect so they're using the same things but they're just using built-in kind of delegates which I'll get to in a second so yeah so click and then when they subscribe to it by saying ok we're subscribing to this is our of that our delegate event handler which we'll get to in a second and we're passing in this function as our event handler they stop button one click as you can see button one not click or but I want underscore click is right here and these are the the the guideline parameters so the event handler now dotnet also supplies us a generic and a non-generic which I didn't teach generic said so I can't really go into detail with this yet but they supply a generic and non-generic event handler that follows the guidelines of their guidelines for events so as you can see this I'm subscribed to this event and I'm using the event handler the event handler delegate and if I right click and hit peak definition which is a new feature of Visual Studio 2013 it me to see that the event handler delegate is defined to follow the standards also an object sender and event args II now they're doing it this way remember there's all different syntaxes with doing this I could simply let's see if I can modify this let's see let's have some fun if I take this out yeah okay let's hurry run oh me putting a message as you can see it still works right so there's all different forms to events right you know I showed you a few of them like you don't have to supply the delegate you have to say new you can just infer by using the method group conversion you can just it will infer and automatically inject the call to new if I just pass in a function I could also what else could I do here if I didn't want to say oh this button got click on this stop button one click if I didn't want to pass in the function what else could I do here I could oh I could do a lambda expression but my lambda expression would have to follow the guidelines because the event requires that so how would I do this if I go let's say object and event args if I don't like that goes but I'll do TT like that try that what happens now as you can see it CT what that lambda expression works so this is just a little off the side kind of thing this represents the object oh and this represents the event handler okay so that's where that happens why is it Aaron well it's not it's not event handle this is event args sorry all right so yeah so this is just a little rant you don't have to that it's not important it's a little kind of cool thing behind the scenes how it works etc but yeah so event handler just like I said if it handle there's a delegate that's already made for us that follows the guidelines that are already follows the guidelines dotnet so if you want you don't have to create your own delegates you can just use the basic generic or non generic event handler delegate that's already made for us whatever one makes you happy okay but that's it for this lesson so we went over delegates anonymous message Slams expressions events and then we talked about a little bit of don''t standards and this generic and non-generic built-in delegate called event args which follows the dotnet guidelines so yeah that's it for this lesson I hope you guys enjoyed it if you have any questions be sure to leave a comment and if whatever you want to see next you could also leave a comment with that and I'll think about it I think I don't know what I'm doing next for this series of videos I'm not sure yet but yeah anyway thanks for watching
Info
Channel: Jesse Dietrichson
Views: 134,650
Rating: undefined out of 5
Keywords: c#, Programming, Advanced, Training, tutorial, Delegates, Events, Anonymous Methods, Lambda expressions, Eventhandler, EventArgs
Id: 8e2GEFNctwQ
Channel Id: undefined
Length: 69min 17sec (4157 seconds)
Published: Sun Nov 10 2013
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.