Generic Delegate Types - CSharp Custom Type

CSharp examples for Custom Type:delegate

Introduction

A delegate type may contain generic type parameters. For example:

                                                                                                    
                                                                                                      
public delegate T Transformer<T> (T arg);

With this definition, we can write a generalized Transform utility method that works on any type:

Demo Code

using System;//w  ww.  ja  v  a2 s.  c om
public delegate T Transformer<T> (T arg);
public class Util
{
   public static void Transform<T> (T[] values, Transformer<T> 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.Transform (values, Square);      // Hook in Square
         foreach (int i in values)
            Console.Write (i + "  ");           // 1   4   9
         }
         static int Square (int x) => x * x;
}

Result


Related Tutorials