CSharp - Writing Plug-in Methods with Delegates


A delegate is useful for writing plug-in methods.

In the following code we create a utility method named Convert that applies a transform to each element in an integer array.

The Convert method has a delegate parameter, for specifying a plug-in transform.

Convert method is a higher-order function, because it's a function that takes a function as an argument.


using System;
delegate int ConverterFunction (int x);

class Util//from   www  .  j  a v a 2s.co  m
       public static void Convert (int[] values, ConverterFunction t)
         for (int i = 0; i < values.Length; i++)
           values[i] = t (values[i]);

class Test
       static void Main()
         int[] values = { 1, 2, 3 };
         Util.Convert (values, Square);      // Hook in the Square method
         foreach (int i in values)
           Console.Write (i + "  ");           // 1   4   9

       static int Square (int x) => x * x;


Related Topic