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!

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

Top comments (0)

👋 Kindness is contagious

Immerse yourself in a wealth of knowledge with this piece, supported by the inclusive DEV Community—every developer, no matter where they are in their journey, is invited to contribute to our collective wisdom.

A simple “thank you” goes a long way—express your gratitude below in the comments!

Gathering insights enriches our journey on DEV and fortifies our community ties. Did you find this article valuable? Taking a moment to thank the author can have a significant impact.

Okay