C# Func and Action

In this chapter you will learn:

  1. How to use Func and Action from system namespace
  2. Example for C# Func and Action

Func and Action from System namespace

C# System namespace defines several generic delegates to convert almost all possible method signatures.


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);
/*from   w w  w .j  a  v a  2s .co  m*/
... 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

Example

We can rewrite the printer delegate as follows.


/*www.  ja  va  2s  . c o m*/
using System;
class Test
{
    static void output(int[] intArray, Action<int> p)
    {
        foreach (int i in intArray)
        {
            p(i);
        }
    }
    static void consolePrinterInt(int i)
    {
        Console.WriteLine(i);
    }
    static void Main()
    {
        Action<int> p = consolePrinterInt;
        int[] intArray = new int[] { 1, 2, 3 };
        output(intArray, p);
    }
}

The output:

Next chapter...

What you will learn in the next chapter:

  1. Define an anonymous method with the delegate keyword
  2. for loop in an anonymous delegate
  3. Anonymous delegate with parameter
Home »
  C# Tutorial »
    C# Types »
      C# Delegate
C# Delegate
C# Multicast Delegates
delegate parameters
C# Generic delegate
C# Func and Action
C# Anonymous delegate