Delegates — Using Delegates
Delegate is a type that represents references to methods. To create a method is quite simlar with creating delegates. Delegate have a return type and can take parameters. To declare a delegate a written example is could be:
public delegate int MyDelegate(int a);
As seen in the above example, the structure of a delegate is: [access modifier] delegate [return type] [delegate name]([parameters]);
That's how we can create a delegate method. We just need to give the same parameters and return type to the methods with the delegate. A delegate can hold multiple methods.
We said that a “delegate is a type that represents references to methods,” and we just learned how to create a delegate. Now, let’s make examples to understand delegates better.
public class Program
{
public delegate void MyDelegate(); //Declaring a delegate which does not
//takes parameters and dont have return type
public MyDelegate myDelegate;//creating object
void FirstMethod()
{
Console.WriteLine("First method");
}
void SecondMethod()
{
Console.WriteLine("Second method");
}
void CallMethods()
{
myDelegate = FirstMethod; //delegate has FirstMethod reference enymore
myDelegate(); //calling the delegate
}
private static void Main(string[] args)
{
new Program().CallMethods();
}
}
output:
First method
We have created a delegate which is void(does not return any value) and not taking any paramters. And we have created two methods and both of them are void and not taking any paramters. That’s mean we can hold the references to this methods with the delegate which we have created.
And that’s how we added the FirstMethod reference to myDelgate myDelegate = FirstMethod; even if our method would take paramterswe still would not because delegate and methods are have same return type and paramters and when we add the method’s reference to the delegate if there is any paramter we are giving it when we call the delegate to run.
Lets make another example of above explanation:
public delegate void MyDelegate2(int x, int y);
public MyDelegate2 myDelegat2;
int FirstMethod(int x, int y)
{
Console.WriteLine("x + y is");
return x + y;
}
int SecondMethod(int x, int y)
{
Console.WriteLine("x - y is");
return x - y;
}
void CallMethods()
{
myDelegat2 = FirstMethod;
myDelegat2 += SecondMethod;
Console.WriteLine(myDelegat2.Invoke(3, 4));
}
oupu:
x + y is
x - y is
-1
Now our delegate is returning integer and taking two integer parameters. And we can call the delegate with Invoke method too. It will call and run the delegate references methods. and we can add the same delegate other methods too. We can just do that by writing += operator. Or we can delete any reference method in delete by -= operator. And if you check the example’s ouput two methods will work when we invoke the delegate but the returning output will be the latest methods returning value because it is which we have the updated return value.
If we want to see both methods return values by delegate we can can do that by updating CallMethods
void CallMethods()
{
myDelegat2 = FirstMethod;
myDelegat2 += SecondMethod;
Delegate[] del = myDelegat2.GetInvocationList();
for (int i=0; i< del.Length;i++)
{
Console.WriteLine(((MyDelegate2)del[i]).Invoke(3,2));
}
}
ouput:
x + y is
5
x - y is
1
Now we can see both methods return results. By putting each delegate method in a delegate list and calling each method.
Especially when there are more than one implemantation in a class we can create a delegate and make the methods type and parameters same on method with delegate. Thats a case where we prefer to use delegate.
Now lets make another example which shows more than one implemantation for
public class AnotherExample
{
public bool LessThanfive(int x) { if (x < 5) return true; return false; }
public bool LessThanthree(int x) { if (x < 3) return true; return false; }
public bool LessThanteen(int x) { if (x < 10) return true; return false; }
public delegate bool CheckValue(int number);
public IEnumerable<int> CountLessThan(IEnumerable<int> nums, CheckValue value)
{
foreach (int number in nums)
{
if(value(number))
{
yield return number;
}
}
}
}
//Main class where we run the project:
private static void Main(string[] args)
{
AnotherExample obj = new AnotherExample();
int[] nums = { 1, 2, 3, 4,7,8 };
var res = obj.CountLessThan(nums, obj.LessThanthree);
foreach (int i in res)
Console.WriteLine(i);
}
In that example: we have created created 3 different methods: LessThanfive, LessThanthree, and LessThanteen
public bool LessThanfive(int x) { if (x < 5) return true; return false; }
public bool LessThanthree(int x) { if (x < 3) return true; return false; }
public bool LessThanteen(int x) { if (x < 10) return true; return false; }
They are all just take a parameter and make the control if they are less than parameter or not and returns true or false. and we have created a delegate method too.
public delegate bool CheckValue(int number);
We have created delegate CheckValue and it return same type with our models which is bool.
And created a method which is taking an integer list and delegate as a parameter.
public IEnumerable<int> CountLessThan(IEnumerable<int> nums, CheckValue value)
{
foreach (int number in nums)
{
if(value(number))
{
yield return number;
}
}
}
And we have sent CheckValue delegate as the parameter let us to change it easily when we call it.
obj.CountLessThan(nums, obj.LessThanthree);
So now in this code blog if we change LessThanthree to LessThanteen it will check and return values which is bigger than 10. Thats how we can use delegate in a different example. We used the delegate as the paramter so that we can send different same type methods and make more than one implemantation in one class. That was some other way to use it.v
I hope the article was helpful for you to understand what is delegate and see different examples to understand the purpose to use it.
If you think it was a good and clear article for explain delegates, do not forget to claps and follow. Hope to see you soon on new articles :)