With delegates you can pass methods as argument a to other methods.
The delegate object holds references to other methods and that reference can be passed as arguments.
This is a key functionality when working within the functional programming paradigm.
We can create callbacks by utilizing this technique.
A function that receives one more multiple functions as argument or/and returns a function is called higher order functions.
Below is an example of a Map function that receives a int array and a callback function. You can then customize the callback to modify each element in the array. The Map method returns a new array with each item modified.
class Program {
// define Callback delegate obj
public delegate int Callback(int valueToModify);
// Map function that takes a cb to modify each item in array and returns a new modified array
public static int[] Map(int[] arr, Callback callback) {
int[] newArr = new int[arr.Length];
for (int i = 0; i < arr.Length; i++) {
newArr[i] = callback(arr[i]);
}
return newArr;
}
public static void Main (string[] args) {
// Create custom callback
Callback squareNumbers = x => x * x;
int[] arr = {1, 2, 3, 4, 5};
// pass the custom cb as arg
int[] squaredArr = Map(arr, squareNumbers);
foreach (int num in squaredArr) {
Console.WriteLine(num);
}
}
}
You can now play around with this a feel free to define your callback with a lambda function as we learned in the last chapter.
Happy Coding!
Top comments (0)