C# Action & Func

Action objects return no values. The Action type in the C# language is similar to a void method.

using System;

class Program
{
    static void Main()
    {
 // Example Action instances.
 // ... First example uses one parameter.
 // ... Second example uses two parameters.
 // ... Third example uses no parameter.
 // ... None have results.
 Action<int> example1 =
     (int x) => Console.WriteLine("Write {0}", x);
 Action<int, int> example2 =
     (x, y) => Console.WriteLine("Write {0} and {1}", x, y);
 Action example3 =
     () => Console.WriteLine("Done");
 // Call the anonymous methods.
 example1.Invoke(1);
 example2.Invoke(2, 3);
 example3.Invoke();
    }
}

Output

Write 1
Write 2 and 3
Done


Func handles many arguments. The Func type is a parameterized type. We specify the number and kinds of parameters, and the type of the return value. The Func type provides a way to store anonymous methods in a generalized and simple way.

using System;

class Program
{
    static void Main()
    {
 //
 // Create a Func instance that has one parameter and one return value.
 // ... Parameter is an integer, result value is a string.
 //
 Func<int, string> func1 = (x) => string.Format("string = {0}", x);
 //
 // Func instance with two parameters and one result.
 // ... Receives bool and int, returns string.
 //
 Func<bool, int, string> func2 = (b, x) =>
     string.Format("string = {0} and {1}", b, x);
 //
 // Func instance that has no parameters and one result value.
 //
 Func<double> func3 = () => Math.PI / 2;

 //
 // Call the Invoke instance method on the anonymous functions.
 //
 Console.WriteLine(func1.Invoke(5));
 Console.WriteLine(func2.Invoke(true, 10));
 Console.WriteLine(func3.Invoke());
    }
}

Output

string = 5
string = True and 10
1.5707963267949

The first Func receives an int and returns a string and it is declared as Func<int, string>. The second receives a bool and an int and returns a string. It is declared as Func<bool, int, string>. The third simply returns a value.

留言