DEV Community

Emanuel Gustafzon
Emanuel Gustafzon

Posted on

2

C# pass delegate methods as arguments.

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);
      }
    }
}
Enter fullscreen mode Exit fullscreen mode

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!

Sentry image

See why 4M developers consider Sentry, “not bad.”

Fixing code doesn’t have to be the worst part of your day. Learn how Sentry can help.

Learn more

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay