Movatterモバイル変換


[0]ホーム

URL:


Skip to content
DEV Community
Log in Create account

DEV Community

Emanuel Gustafzon
Emanuel Gustafzon

Posted on

     

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 modeExit 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!

Top comments(0)

Subscribe
pic
Create template

Templates let you quickly answer FAQs or store snippets for re-use.

Dismiss

Are you sure you want to hide this comment? It will become hidden in your post, but will still be visible via the comment'spermalink.

For further actions, you may consider blocking this person and/orreporting abuse

Hi 👋, I am a passionate developer and I am looking forward to sharing my knowledge here on Dev. It’s great for myself and others to get a deeper understanding of software development.
  • Location
    Gothenburg, Sweden
  • Education
    Code Institute and .Net Developer at EC Utbildningen
  • Joined

More fromEmanuel Gustafzon

DEV Community

We're a place where coders share, stay up-to-date and grow their careers.

Log in Create account

[8]ページ先頭

©2009-2025 Movatter.jp