Writing Plug-in Methods with Delegates - CSharp Custom Type

CSharp examples for Custom Type:delegate

Introduction

A delegate variable is assigned a method at runtime.

Demo Code

using System;// w w w.  j  a v  a 2 s .  co m
public delegate int Transformer (int x);
class Util
{
   public static void Transform (int[] values, Transformer 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 the Square method
         foreach (int i in values)
            Console.Write (i + "  ");           // 1   4   9
         }
         static int Square (int x) => x * x;
}

Result


Related Tutorials