In this article we will be discussing C# delegates. On this episode we will explore and dig deep into delegates, what are they and how do they work. We will explore Actions and Func and we will see how we can use delegates in a real life scenarios. Show You can watch the full video on YouTube And you can get the
full source code from GitHub: So what we will cover today:
As always please comment your questions, clarifications and suggestions in the comments down below. Please like, share and subscribe if you like the video. It will really help the channel Ingredients
Delegate are defined outside of classes, they are their own entity. When i want to create a delegate i can create the same way i create a class. We can create the delegate in the same file as our project outside the class, but based on the .Net documentations delegate should be created seperatly in a seperate file. And based on personal experience its always better to use delegates with class libraries we will discuss the reasonning behind it in our real world scenario. So what exactly is a delegate? In order for use to understand delegates let us see how normal variables work.
Enter fullscreen mode Exit fullscreen mode We can see with variables we can assign them to different variables, we can pass them to methods and we can utilise extension methods to do some work on these variables. Delegates offers us the same flexibility but for methods, i know this might sound a bit confusing but let us delve deep and understand how we can use it and why we want to use it. Delegates is to store methods as variables. When i create a delegate i need to provide a signature of what type of method i need to store inside that delegate. We can think about it as an interface, its like a contract which we need to follow so we can use it.
Enter fullscreen mode Exit fullscreen mode Let us analyse this initialisation:
So what does that mean, it means that i will be able to store methods which have the same signatures (parameters and return type) inside this delegate. So how can we can utilise the methods in the delegate, it is very simple we initialise the delegate in the same way we initialise a class
Enter fullscreen mode Exit fullscreen mode We pass to the delegate the method that we want to store as a variable. And if i want to execute the method inside the delegate all i need is just pass the parameter i want and the delegate will do the work. So far it seems its no different why would i need to do this if i can just call the method directly, the power of delegate comes in
passing the methods around our code. Let us see the below example and see how it is being utilised
Enter fullscreen mode Exit fullscreen mode The cool this about this is we can see we are passing a complete method to another method and then utilising it, this is the power or delegate. This will allow us to create abstract calls just by using delegates and avoid using if else statement which will allow us to follow the SOLID principles better Delegates are typed checked, they are strongly typed In a delegate we can store multiple methods, its not a single method so when i invoke a delegate each one of these methods will be invoked in the same order they were added to the delegate We can utilise the += operator to add more methods to a delegate, we can add as many methods that we want as long as we have the same parameter and return types for the method.
Enter fullscreen mode Exit fullscreen mode We can also remove methods from a delegate to do that we need to utilise -= operator
Enter fullscreen mode Exit fullscreen mode As well with delegates we can utilise anonymous functions
Enter fullscreen mode Exit fullscreen mode The down side of using a lambda function or an anonymous function inside a delegate is that we canno remove them from the delegate. Another way we can invole delegate is as follow
Enter fullscreen mode Exit fullscreen mode There is also DynamicInvoke which is slower then the previous 2 but it is used when we are not sure about the delegate we are using.
Enter fullscreen mode Exit fullscreen mode So what is happening in this method:
Enter fullscreen mode Exit fullscreen mode Action & Func Actions are built in delegates which allows us to have void methods and up to 16 parameters When ever we want to use a delegate without a return type we should use actions
Enter fullscreen mode Exit fullscreen mode If we want our methods to have parameters we should use the generic version of the actions
Enter fullscreen mode Exit fullscreen mode More advance case
Enter fullscreen mode Exit fullscreen mode Func is almost the same as an action but the main difference is that it has a return type, a none void method. In order to use func they must have the following rules, the last generic parameter is the return type we want to save.
Enter fullscreen mode Exit fullscreen mode if we call multiple methods inside the func it will only return the last value, it will execute all of the methods but the return will be from only the last method called. Now lets see how we can add parameters to the func, its an easy implementaion
Enter fullscreen mode Exit fullscreen mode Utilising Func in an annonymous functions
Enter fullscreen mode Exit fullscreen mode Now lets see it in a real case scenarios Lets create a new console application
Enter fullscreen mode Exit fullscreen mode And now let us create a class library which we will use to store our models
Enter fullscreen mode Exit fullscreen mode Now let us add reference to GradesApplication from GradingLib
Enter fullscreen mode Exit fullscreen mode Now let us open our code in visual studio code. The first thing we need to do is add a folder in the root of GradingLib classlib and call it Models. Inside the Models folder let us create our first Model Student and add the following
Enter fullscreen mode Exit fullscreen mode Now let us create another Model called Exam
Enter fullscreen mode Exit fullscreen mode Now inside the Program.cs in our GradingApplication let us add the following
Enter fullscreen mode Exit fullscreen mode Now let us implement some delegate inside our application, we want to get the highest grade while we do the average grade calculation and to accomplish this we will use Delegates. lets navigate to Exam.cs inside the Models folder and add the following
Enter fullscreen mode Exit fullscreen mode And let us update our program.cs so we can utilise the delegate
Enter fullscreen mode Exit fullscreen mode Now if we run our application we can see that we get our grades as expected the avarage and the highest grade The next step we will add a new delegate which will allow us to see how we can make our code more extensible. We will inject functionality to our classlibrary without the need to update it using delegates. Will start by
updating the Exam.cs Model we will add a new method to allow us to see if the student has passed or not based on certain conditions we will nee to add the following
Enter fullscreen mode Exit fullscreen mode We can see here only the students who got 70 or above has passed. but there one thing that which is not quite good about this what happens if we want to change the passing condition from 70 to 65 or to 75? We will need to update the hard coded code and build our application again and redeploy it. This is not the ideal scenario One of best scenarios is to implement delegates to fix these issues. Let us first start by adding a delegate in a new file called PassingCondition
Enter fullscreen mode Exit fullscreen mode This delegate will contain the conditions that we want to check to check weather the students has passed or failed. Next we need to update our passStudents method to accept delegates as follow:
Enter fullscreen mode Exit fullscreen mode Now inside our Program.cs inside our GradingApplication we need to add the following
Enter fullscreen mode Exit fullscreen mode A method that will have the grading criteria. And the way we call the exam.PassStudents to the following
Enter fullscreen mode Exit fullscreen mode Now we can run the application and we can see that we are getting the expected results. Now lets say we want to update the passing grade from 70 to 75 we wont need to update the classlibrary all we need to is update our conditions in the console app and it should work. Which delegate can hold and invoke multiple methods?If a delegate has do not return any value, it is a multicast delegate that can invoke multiple methods.
Can single delegate invoke more than one method?A single delegate can invoke more than one method.
What is multi cast delegate?The multicast delegate contains a list of the assigned delegates. When the multicast delegate is called, it invokes the delegates in the list, in order. Only delegates of the same type can be combined. The - operator can be used to remove a component delegate from a multicast delegate.
What is a callback delegate?Callback by Delegate
Delegate provides a way to pass a method as argument to other method. To create a Callback in C#, function address will be passed inside a variable. So, this can be achieved by using Delegate.
|