Delegates & Multicast Delegates in C#.Net made easy! | Action & Func | Anonymous Methods

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
[Music] hi friends welcome to another video of code Allegiant in this video we'll be exploring delegates in c-sharp dotnet so these are topics which we'll be covering today first we will see what exactly is simple delegate then we will see how we can create anonymous methods using delegates then we'll understand what is multicast delegates and then we will see how create can create callbacks using delegates then we will see how we can make extensible and flexible applications with the help of delegates and finally we will just touch upon action and func so let's start with simple delegates so what exactly is a delegate as per Microsoft a type that represents references to methods is nothing but a delegate or we can say in different words like an object that knows how to call a method this is actually very helpful while designing extensible and flexible applications so that we will be seeing very soon so on the right side you can see how we can create a delegate doclet provides the keyword delegate so you can see this explanation here so if we are creating public delegate the return type is void and the name of the limit and the parameter is string message so what exactly this means so this means this delegate is an object or a reference which can take any method of this signature that means any method which is having a void return type and a single parameter of string type can be assigned to this delegate so we can use this delegate in this way we can say print delegate the name of the delegate which we gave and some object instance name and we can assign any method of this signature to this particular instance and how we can call this by just invoking this object and passing the parameter so let's see in action how exactly it works so I am in Visual Studio and this is a simple console application which have created and in the main method I have just one statement console dot read line that is it will wait for my input from the console so let's start with creating and telling it so when you say public delegate you can see there is a keyword which the dotnet is offering just telling it then I have to tell the return type as of now I will keep it as void then I will create maybe my delegate this is the name of my delegate and then I have to tell what are my parameters so as of now I will not pass any parameters so it is a simple delicate now I will create another method public static void maybe you say with method one and in which we are doing just a simple console.writeline saying this is method one so now I can create instances of my delegate just by just saying they my delegate d1 equal to I can assign any method which follows this signature that is return type void and takes no arguments so this method satisfies that so I can just say method one and to invoke that I can say D one and that's it this is the way you create a delegate and invoke it so when you run it internally it will call that method now suppose you want to change the signature of this method I want to pass a parameter into I so I have to change the signature of the delegate also to take a parameter maybe cell change the name so int one in type and when you are calling the instance of the delegate you will pass a value so when you run it calls OH so to verify that we can print this value here maybe I will print I here so now when you check you can see the value which you past violent working the method so this you can call multiple times by passing different values be one again I'll call with some forty five so now I've called three times so you can see the method has been called three times with different values so this is how a simple delegate works this delegate is helpful in creating anonymous methods as well for example if you think this method is too small and you don't have much functionality here and you don't want to create a separate named method there is a way you can create an anonymous method as well so let's see an example for that I'll remove these methods and these from here I am changing my delegate such that it returns me a hint and takes one end and here I'll create the instance for example Square and here I'll create the anonymous method so for that you need to use keyword delegate which takes an argument off into type and I will give the body of the method here itself so this will return me n into n so that means I am taking the square of the method I can create similar way one more instance of my delegate which says cube where again I'll use the anonymous method which takes int n and this guy returns me n into n into n so this gives me the cube so now wherever you want to call these methods you can use this references of Delegates so for example I can say console dot readline square of five I can say console dot write line cube of five and I can say console dot write line maybe again cube of some seven and just to run it so you can see the value 25 125 343 so this is how you can create anonymous methods using delegate now since that you have understood what exactly is simple delegate let's see what is multicast it gets so it is just an extension of the simple delegates so multicast delegates is nothing but multiple objects of delegates can be combined together using plus operator so like how you do arithmetic operators on int type you can do on delegates type and you can do even minus operator to remove the delegates so once multiple objects of delegates are added together and you call that delegate once all those which are added into the list will be called so you not clear with it let's see an example we have a delegate called print delegate which returns white and takes one message I have any method which has the same signature if I have three forcing methods so I can use them like print delegate instance one as method one print delegate instance two as method two and I can create print delegate instance three which adds these two delegates so that is instance one plus instance two and when I invoke instance three with some parameter internally it invokes both of them so let's see this work in action I am in visual studio and this is one simple console application so first I will create a delegate public delegate sorry and return it as white and I will name it as delegate and this guy takes maybe int parameter and in the simple delegate with section we have seen how we can create simple delegates for this so like my delegate d1 and I can assign a method so instead what I do first I will create two methods that is public static void may be method one which takes in I and I will just print method one and the value which I have passed that is I so now I'll just copy this and create one more method and I'll name it as method two and I will print method 2 on the console from this method now I will create three references for my telling it and this should be t2 now what I'll do is d1 I'll assign method 1 d2 I will assign method 2 and now when I say b3 I will say D 1 plus D 2 that is combining these two instances into one now when you invoke d3 with suppose a value of 5 and you run this you will see both method 1 and Method 2 getting called with the same parameter value so this is how a multicast delegate works so you can instead of the plus operator you can use minus operator also so now as you can as you know that d3 contains both d1 and d2 now I want to remove d1 from this list so I will say three equal to D 3 minus B 1 so now from this D 3 list D 1 will be removed and now if I call d3 with some some different value and when you run you can see only method 2 gets called because method 1 has been deleted from the list so this is how you can perform plus and minus on delegates so this can be shortened it normally in usual applications we don't use these kind of methods additions we normally use plus equal to operator so that you know in with integer parameters you can use I is equal to I plus 1 as I easy I plus equal to 1 so that means if I have the D 1 which I want to say D 1 plus D 2 instead of writing like this I can say D 1 plus equal to D 2 so this is a shorthand way of writing this particular statement so we can use similar way that is and remove all these and I will keep only one reference that is D 1 now I'll say D 1 equal to method 1 and then I'll say D 1 plus equal to method 2 and for just a demo purpose I will create one more method say method 3 and I will just print method 3 and here I will say D 1 plus equal to method 3 so now I have assigned three methods to one delegate reference so now when I invoke D 1 with some value 7 you can see all the 3 methods get called and similarly given you can use d1 - equal to and I might map I'll remove method - and I'll again called e1 with some different value so now you see you can see only method 1 method 3 getting called method 2 has been removed from the list so this is how a simple multicast delegate works now let's see how we can create callback methods using delegates so what exactly is callback as per Wikipedia definition callback is an executable code that is passed as an argument to another code that is expected to call back or execute the argument at any given time let's try to understand this with an example I'm in Visual Studio and this is a control application so this is the default class program and I have a main method suppose this is another library and in that some class is there and there is a method which does some very time-consuming works so basically this does some big work so this can be in the real time like might be you want to access some server or calls and web api is or contact the database or read something from the network or whatever like which takes a lot of time so normally in general case when you are doing such type of thing you don't want your main thread or in the case of a GUI application it will be the window you don't want the window to freeze and you don't want the main thread to wait till this work is completed in such cases you create a thread and call this method using a different thread but suppose after calling this this guy does some work and that result you want to send it back to the main thread or in the case of a UI you want to pop up a message saying that the data is so and so which we have written retrieved so in such case delegate comes in to help and such kind of calling of methods isn't called callback so from here I'll create a thread and start this method but once this work is done I will give a call back with some data to my main thread so to do that in this class we will create first a delegate so a public delegate void may be some name called work handler and this guy expects some int I variable so this can be anything like I have I want to return a int type to the calling method so that's why I have used and it can be a string or whatever type of data you want to send back so here to do some big work I'll use thread don't sleep 5 seconds so this simulates a very big work and this method expects a work handler type method to be called so that means whoever is calling this method from anywhere needs to pass a method which satisfies this signature of having a return type void and a parameter of interp so if that kind of method is passed to this method it will accept it and at the end after doing the work and simply call this method with whatever value I want to return it so in this case I am just passing a dummy value maybe that value will be like extracted from the database or get it from the server or network whatever that value you will pass back to this method so you are calling this method with that now from the main what we'll do is first we'll create the object of this slab library class so that is maybe some object equal to new object new class and I will say maybe I can start a different thread so I'll say T is equal to new thread and I'll use a lambda expression so if you are not clear with lambda expression you can check out my other videos where I have explained lambda expressions in detail so in this method I will just call obj . do some time-consuming work and it expects a method so what method I will create here of the same signature which this delegate is expecting so that is like public void maybe print method which expects an integer and in this simply I'll print the value so maybe I can put the value is I but since we are dealing with static methods i will create this method as static so that i can directly use it in the main and here as a parameter i will pass this parent method so this is how i create a third and I will simply say t dot start so now just to make sure that we are not stuck there I will say console dot write line we are still alive in main thread so this is a print which happens after the thread has started so now if you see the flow in the main method I have create another used another library class and in that object using that object I have a method which I can call but I am calling that in a new thread and this method expects a type of method which should be of void return type and has takes an argument of inter type so this is the method which I am passing here in this class we are expecting that same method and I am doing some big work for 5 seconds and then just I am giving a call back to this method with some return value so now when I call this method maybe in the beginning I can put one console application console.writeline so that you can see code begins here so that in the console we can see something is happening so when I run this you can see first it will print code begins here and it goes we are still alive in the main thread so that thread has not been killed but you see after some time a value has been returned so this is nothing but a callback so you are from this method you are giving a call to another method and you are not stopping for that method to return any value you continue in the main thread but once the work is done this method gives a call back to the main thread with some value so this is how a callback method works now we will see how we can use delegates from making flexible or extensible applications so let's jump into visual studio and this is some console application which I have created which does just has a main method so now let's see what we can do you can right click and I will add a new class maybe I'll create a class called photo so since these days everyone is using cameras in mobiles and you everyone will be using applications like Instagram Facebook where people keep uploading photos and everyone try to process them like they'll change the color they will apply some filters etc so I will try to replicate that similar scenario here so maybe I you as you can see the program dot C s is in namespace delegates demo I will create another namespace just to demonstrate like it's in a different library so I will say my photo application so I have this as a library called my foot application and in that I have a public class called photo and this photo has one property called name so this is nothing but a photo now I'll create another class in the same library which is like process photo or maybe first I'll create some photo filters so this is an application which you are offering to customers so I will create public class filters and I will create public static void some method called apply saturation this guy accepts of photo and inside I'll just have a print saying saturation applied and the name of the photo so maybe P dot name similarly I can have one more method saying apply contrast and I will say contrast applied to this photo so there's another one so I'll move this guy to another file called photo filters dot CS so now we have photo dot C as float of filters dot CS both of them in the same namespace called my photo application and now I'll create one more class called public maybe something like process photo I'll make this guy as public and here I will have a method called public void process so this is a simple method so now the delegates come into picture now I want to make this application more robust so like so that when I offer this library to any customer they can have the flexibility of expanding it so how it happens I will show you now you create first a public delegate maybe a void type and some photo filter handler and this guy expects a photo type now this process method expects a method of type void return type and which expects an integer and parameter called photo so I'll use this delegate that is photo filter handler and some variable name called handler so I will also expect one photo argument so maybe I'll first start except that photo and with that I will expect a method so this guy's work is just to call this handler method and pass this argument to that so handler of photo and that's it so I will move this class also to different CS file that is photo process photo dot CS now this library when you give to some customer so first I will use I'll use them in namespace of name using my photo application so now you I am using someone's library and here what I can do is I can create a photo plus photo is equal to new photo and I will save photo dot name is equal to maybe some landscape dot jpg this is just to simulate a real-time application kind of scenario so now my photo is ready now I want to process it so what I'll do is I will call I'll have one more class that is processed photo so I'll save process equal to new process photo and you know very well there is a method called process dot process so which expects a tight photo so I can call this by passing the photo and I want to apply the handlers so that is some filters so you know very well we have created already photo filters class so I will just use photo filters dot apply contrast again I'll say process dot process and I will pass the same photo and say photo filters dot apply saturation now when you execute this what you will see is contrast applied to this landscape dot jpg saturation applied to landscape dot jpg so now everything works fine but now you will have a question why we have to use this delegate instead why can't we clearly directly call that so what is the advantage which we get by using delegates the advantage is what you are going to see next now if you not have given this delegate and you just have given the option of calling this process method by photo and internal you would have applied a contrast the application is limited you are not giving a scope to extend it but with this delete I have the scope of extending it the customer can extend this application like you are not offering something like apply colors but the customer wants now to extend this same application with applying colors so what I can do is I can create a public static void method called applied colors which follows the same syntax of photo some variable here what I'll do is I'll print console dot write line apply maybe then I'll follow like colors applied from outside the library to I'll pass the photo variable dot name so now I have the way now I have a way to extend this like I can say process dot process I will pass the same photo but instead of calling now the method from the library I will call the local method that is apply colors and now when you run you see that contrast and saturation has been applied to that jpg from inside the library whereas colors has been applied to the same jpg from outside the library so now you have the flexibility of making this library which you have offered to the customer the customer can extend it however he wants so this is one of the great ways which delegate offers you to make flexible and extensible applications so the last topic for today is action and func so let's see what exactly is this action and func as you can see on the left side I have explained these are inbuilt delegates offered by dotnet framework so delegate is nothing but reference to any method so action accepts a method which doesn't return any value whereas func accepts a method which it returns a value and both action and func can accept parameters from 0 up to 16 parameters so how you use them is shown on the right set you can use the keyword action and in the angular braces you can L what is the data type so in the case of action as I have explained already it expects a parameter but it doesn't return a value if at all you have mentioned something by default this data type is for the parameter so I'll say action int sum variable equal to a method so this method should have the signature which returns nothing that is void and takes a parameter I if at all you want to return some method the value from many methods for example like this where you have method to takes a double parameter and returns a string then you have to use func instead of action so in the func the first parameter in this angular braces is the parameter type second one is the return type so in this func always the last one which you mentioned inside the angular braces will be the return type so for example in another method which takes double and int type parameters and returns a string you'll have to clear create it like func double int and the last has strength so this last string always refers to the return type so let's see how it works I'm in visual studio and here I'll create a sample method like public static method one this guy doesn't return anything and doesn't take any parameters so I'll say console dot write line and say this is a method one so instead of creating delegates and assigning this which we have seen in the case of simple delegate and multicast delegates now I'll say action some AC T equal to method one and I can simply call a CD so this is equivalent way of calling how we do it for delegates so now if you run it you can see it very well calls the method one so this action once you put angular braces you can see there are 16 overloads so first one is the second one is to where parameters third one is three parameters so like that you have so many overloads up to 16 parameters so now I'll show you one more method like for example this is another method called - which takes int I comma int I joined J comma int okay so it is like three parameters so I can create an action which takes int comma int comma int and say AC t2 equal to method two and I can call AC T 2 and this variable executes but yeah you have to pass the parameter so that is like 1 comma 2 comma 3 so now when you call it executes that method similarly if you want to do this for with the return type so I can just duplicate this code and I'll say method 3 and this is method for and I'll print also method 3 and print method for but in this case instead of void I want it to return int type in this case I want to return string type so in this case we will give error because we have to return something so I'll say return 2 and in this case I'll say some XYZ now if we want to do this instead of action you will have to use func so now when you say func and as soon as you start the angular brace you will see the first one by default expects a return type so in the first case the return type of our method is int and it is like func one and I can assign method 3 to it and I can just call func 1 and whatever the value it comes you can accept it any in any variable also variable sum result equal to func 1 so this value which it returns will be taken over here so when you run you can see the func one also is executed similarly if you have more parameters to be passed you can say func and in this case you have three int parameters and one string return type so you'll say int comma int comma int and comma string so this will be fun too which is assigned with method 4 and you can call the method as func 2 and pulse 3 comma 4 comma 5 so now if you see this parameter takes 3 int variables and returns a string type so when you run this method it very well execute so this is how a funk and action you can use which are like inbuilt delegate types in dotnet framework thank you
Info
Channel: CODELLIGENT
Views: 1,553
Rating: undefined out of 5
Keywords: Delegates, C#, Multicast delegates, .net
Id: ZGHBGFLuvmg
Channel Id: undefined
Length: 35min 34sec (2134 seconds)
Published: Fri Feb 21 2020
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.