i was working on a project few days ago , and i was making a recurrence control , and i found that i need to make a certain logic , and within it i need to call a function that knows the recurrence type and get the set of days the appointment will occur on …
in brief , i need to call a function that takes a parameter of type A , and returns type B without dynamically without knowing the function will be called …
Here is an easy example for how to use delegates ;
for example , we need to make a calculator so we need to make the Add , Multiply , Division , Subtraction
and we need to the function to be called dynamically regarding to which operation is selected..
//here we are defining a delegate , the same
Way as declaring functions , but here we don’t implement it
Just a header , with the parameters and the return type…
private delegate double arithmeticOperation();
// we create an instance of this delegate …
arithmeticOperation aOperationDelegate;
//on the submit buttin click we will see what is the operation
I am going to make then makes the delegate object equal to the function
we will need to call later in the code…
The delegate when creating the new instance from it , it takes only the
Name of the function you will need to call…
private void btnEqualSubmit_Click(object sender, EventArgs e)
{
string operation = txtOperation.Text;
switch (operation)
{
case “+”:
aOperationDelegate = new arithmeticOperation(AdditionFunction);
break;
case “-“:
aOperationDelegate = new arithmeticOperation(SubtractionFunction);
break;
case “*”:
aOperationDelegate = new arithmeticOperation(MultiplicationFunction);
break;
case “/”:
aOperationDelegate = new arithmeticOperation(DivisionFunction);
break;
}
if (aOperationDelegate != null)
{
//it will invoke the function it have been assigned to it J
aOperationDelegate.Invoke();
}
}
//these are the functions that must be of the same return type and parameters of the delegate we have declared up…
private double AdditionFunction()
{
return double.Parse(txtNum1.Text) + double.Parse(txtNum2.Text);
}
private double SubtractionFunction()
{
return double.Parse(txtNum1.Text) – double.Parse(txtNum2.Text);
}
private double MultiplicationFunction()
{
return double.Parse(txtNum1.Text) * double.Parse(txtNum2.Text);
}
private double DivisionFunction()
{
return double.Parse(txtNum1.Text) / double.Parse(txtNum2.Text);
}