Func and Action Delegates - CSharp Custom Type

CSharp examples for Custom Type:delegate

Introduction

With generic delegates, we can write a small set of delegate types to work for methods of any return type and any reasonable number of arguments.

These delegates are the Func and Action delegates, defined in the System namespace.

delegate TResult Func <out TResult>                ();
delegate TResult Func <in T, out TResult>          (T arg);
delegate TResult Func <in T1, in T2, out TResult>  (T1 arg1, T2 arg2);
 ... and so on, up to T16
delegate void Action                 ();
delegate void Action <in T>          (T arg);
delegate void Action <in T1, in T2>  (T1 arg1, T2 arg2);
 ... and so on, up to T16

The only practical scenarios not covered by these delegates are ref/out and pointer parameters.

The Transformer delegate can be replaced with a Func delegate that takes a single argument of type T and returns a same-typed value:

Demo Code

using System;/* w ww .  ja va2s  .co  m*/
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