Delegate and Event in C# (An introduction for new .NET Developers)

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
hello everyone and welcome to dotnet course central in today's video i'm going to talk about delegate and event it's a very basic and fundamental concept in c sharp programming language so first in this video i'm going to start explaining what is delegate and then write a class which is going to show some of the delegate feature and then talk about event and how delegates and events work together first let's discuss what is delegate delegate is a type in c sharp it represents a reference to a method like a function pointer so most of the time when you hear about delegate a lot of places it will come up as delegate is a function pointer but in c sharp delegate is essentially a type which represents reference to a particular method that's why sometime it is called it's like a function pointer because it points to a function delegate is declared with a list of parameters zero or many and a return type which can be word when a delegate is instantiated we can map it with any method with compatible signature so the method can be static or non-static to call the underlying method for a particular delegate we can use the invoke function on the delegate or we can just call it with the name of the delegate along with the open close braces signature once i show it it's going to become much more clearer what i mean so to demonstrate this i'm going to create a new dotnet core console application so in this project first i am going to create a new class and the class will be calculator for example and inside of the class i'm going to create a new delegate type so i'm going to say the return of this delegate let's say it's integer and the name is going to be calculate and then let's say it takes a single parameter and next i can create a public method which again returns integer and it is execute and this method is a method which takes this delegate i declared as a parameter and an integer as the second parameter and inside of this function i'm just going to return executing the delegate with the incoming input so as you can see as i just mentioned earlier that we can invoke the delegate using the delegate name open close brace parameter or we can also do the invoke so right now i'm just going to have open close that's how delegate is going to be called now if we want to use this inside of program first let's create a static function here which has the same signature as the delegate which is static in square and it's just going to return input times input and now inside here what we can do is we can create a new instance of the type that we declared and then we can do see the execute method now we want to pass a delegate calculator.calculate to this execute method so there are two ways of doing it the first way is we can say calculator.calculate is equal to square so we essentially declare the calculate and point it to the square function and then we can call calculator dot execute and we can pass calc and five as a parameter and and in the console.output you can see i can do that so now one thing as you can see this is a very important point is that though the delegate is declared as a public member of this type it cannot be accessed through the instance unlike any other public member because delegate is a type and it is little bit different than normal types it behaves like as if you declare a inner class when you declare an inner class it doesn't become a member of the class meaning you cannot do so if i declare a if i declare like this i cannot come here and say calculated instance dot test i have to do calculator dot test similarly the delegate also is success can be accessed using the class name it's more like an inner type than a instance member this is something i wanted to clarify so hence when we access it we cannot access it through the instance because it's not an instance member it's an inner type hence we can access it through this so this is how we can call so this is one way of calling delegate so now if i run this i should see five as the response let me give a console.readline so that we can see the output and we can see that the response is 25 which is 5 times 5 as expected the other way of calling or other way of passing this is instead of declaring it and associating it with square we can just pass square here and we don't need this this will behave the same as before and in my experience delegates are mainly used as callback functions or along with events so that that's what delegate is and i think it gives you a fair enough idea of what delegates are the other interesting thing with delegate is apart from the invoke method you can see there are a couple of methods begin invoke and and invoke the begin invoke and end invoke can be used along with the delegate to make the delegate asynchronous so you can use begin invoke you get a i async result and then you can use the async result in the async callback function to call the end invoke and get the response this is another thing you can do but we don't use it anymore because it is not needed since async await has been introduced but in earlier days beginning vogue and invoke of delegate was pretty popular i'm not going to dive into it i just wanted to show the next thing we are going to talk about action and funk the delegate discussion is not complete if we don't discuss action and funk these are the out of box delegate provided by c sharp so that we don't have to create our own delegate almost ever so in terms of delegate if you think about it at a high level there are only two types of delegates which are possible one type is a delegate that returns a type takes bunch of parameter or no parameter and the other type of delegate is the one that returns nothing and takes punch of parameter or no parameter that part is common but one returns something and one doesn't return anything and that's what action and funk is all about func is a delegate which returns something and it can take up to 16 possible parameter combination so it can be funk of t result in which case it's not taking any parameter or it can be func of t t result func of t1 t2 t result and up till func of t1 t2 t16t result that's funk which is equivalent to a delegate that returns and then we have action an action is a delegate that returns void or doesn't return anything but takes a bunch of parameter so for action the parameter can be again it can be from zero so not taking any parameter or it can be action of t action of t1 t2 and then action of t1 t2 t3 dot dot t16 so let's take a look at the action and funk delegates the out-of-box delegate so if we take this example in the calculator we can completely replace this with a func of int and takes an input as an int and return a output of int and here nothing changes so it is still square because let's take a funk of intent and if we run this it is just going to work as expected now if we want to use along with funk and action what we can do is as i said action is also a delegate so we can either declare something like public delegate void let's say print which takes which takes an input and here we can pass the this can be one parameter and this one here it can so it can use the delegate to print and then finally return and we can come out here and at this point in time for the second delegate we can simply pass console.write and five and we don't need this and now if we run this it is just going to print out and come out and then what we can do is instead of this delegate that we created we can just take here action of int and then we come here run it it should behave exactly the same way so that's about funk and action and since funk and actions are introduced i don't see a reason for ever creating your own delegate because every possible combination is kind of available but the delicate discussion is incomplete without lambda so where does exactly lambda fit in so for that let's first understand what is lambda lambda expression is used to create an anonymous function so it is nothing but an anonymous function but anonymous function in itself is kind of useless anonymous function is usually used with a delegate or to represent a delegate so any delegate type can be represented with a lambda expression the parameter and return type of course has to match lambda can be async this is not related to this discussion but just to mention that lambda can be async or non-async so now here if we have to use lambda expression instead of square we can pass an anonymous type so we can do this that's all and we can get rid of this square now if i run this this is going to give the same response of 25. so it's the exact same thing it's just that instead of declaring a function you just provide an anonymous function and your anonymous function will be called back when you need so that's essentially where the lambda fits in in the whole discussion of delicate is that the delegate representation usually ends up being a lambda i don't remember last when i used a function declaration for a delegate almost always we end up using lambda expression when it comes to declaring a delegate and the final thing for this discussion is event so events as we all know is nothing but something that we trigger to invoke a function the even keyword is used to declare an event in c sharp and unlike delegate which becomes like an enclosed type event is treated as an instance member and that i think is a fundamental difference and an event is always associated with the delegate when an event is read the delegate is called back that's what essentially happens when you rise an event you are basically invoking the delegate the delegate associated with an event usually have two parameters as a standard practice this is not mandatory but as a best practice the delegate associated to event always has two parameter the first parameter is an object representing the instance that raise the event and second parameter is a type representing event arguments so if i have to show this let's go back here now first let's create an event argument so i'm going to go create a new class and we can say calculator event args and usually the naming convention for event argument suffixes with event arcs and i'm just going to give name that's it and now we can go into calculator and here we can declare an event so we can say public event and for event we need a delegate now here what i'm going to do is i'm going to use the action delegate with object as the first type and then the calculator event docs as the next type and then here i'm going to have the name of the delegate called calculate that's it and then what i'm going to do is i'm going to have a public void raise event and in the race event what i'm going to do is i'm going to pass a name and here what i'm going to do is i'm going to say calculate if it is instantiated then invoke and the invoke is as you can see the event.invoke is nothing but invoking the delegate itself because the type of the event is nothing but the delegate so we're going to invoke and here as you can see the first parameter is the object which is raising the event in our case it is going to be this the calculator and the second parameter is going to be new of even dogs and for the name we can pass the incoming name so in this case what we can do is so now we can go here back to the program and then here what we can do is we can do calculator dot calculate and to attach a delegate we use the plus equal to and this there are two options here also either we can declare a delegate like calculate this and here we can say so dot write line of args to dot name and then here we can raise the event calling the raise event and passing a name so that's one option and i'm going to show this fast now remember one thing usually the raising of event does not happen at the place where the subscription happens because it would not make much sense right so usually the calculator might be uh even pass if we want to call it that way which has both publish and subscribe and someone will take the instance and publish and someone else will subscribe to get a call back so this way we can have two component decoupled from each other where one raises event another one listens to an event and you can create an in-memory even bus inside of a type using just plain simple events so now that we have that what we can do is if i run this application now i should see the test name showing up after 25 and then i'm going to show you the usual way we use these we normally use lambda in this case now if i run this application i should see the exact same result as before that's it so that's all i wanted to cover today and as i mentioned at the beginning of this video these are extremely basic concepts but this is a very important concept for someone who is new developer to c-sharp hence i thought i'll just cover this couple of topics if you like this video please give me a thumbs up and if you are new to my channel if you think you are going to get value out of my channel please subscribe to my channel and thanks so much for watching this video
Info
Channel: DotNet Core Central
Views: 7,240
Rating: undefined out of 5
Keywords: delegate c#, event c#, delegate .net core, event .net core, delegate .net 5, event .net 5, delegate .net framework, event .net framework, delegate and event, delegate and event in c#, delegate and event in .net, delegate and event in .net core
Id: xr2C4f5bRZM
Channel Id: undefined
Length: 19min 6sec (1146 seconds)
Published: Sun Feb 14 2021
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.