BlackWaspTM

This web site uses cookies. By using the site you accept the cookie policy.This message is for compliance with the UK ICO law.

.NET Framework
.NET 3.5+

Func and Action Delegates

The Func and Action generic delegates were introduced in the .NET framework version 3.5. They provide flexible delegates with generic parameters that can be used for many purposes, including passing lambda expressions to method parameters.

Using Generic Delegates as Parameter Types

The Func delegate is commonly used as the type for parameters of methods that accept lambda expressions. These include LINQ standard query operators and similar methods that you create in your own projects. We will demonstrate this with this article's final example.

The following method defines an array containing the names of ten fruits. The method returns a filtered list of these fruits based upon the delegate passed as the only argument. Note that the types assigned to the Func delegate specify that the encapsulated method must receive a single string parameter and return a Boolean value. We could execute the passed method against each fruit string in a for-each loop. However, for simplicity the example uses the "Where" query operator.

private static string[] Fruit(Func<string, bool> filter)
{
    string[] fruit = new string[]
        { "Apple", "Banana", "Cherry", "Damson", "Elderberry", "Fig", "Grapefruit",
          "Huckleberry", "Lemon", "Mango" };
    return fruit.Where(filter).ToArray();
}

To test the method, add the following code to the Main method of a console application. This code calls the Fruit method, applying a filter that returns only fruit with a name shorter than six characters. The fruit names are then outputted.

string[] shortFruit = Fruit(f => f.Length < 6);
foreach (string fruit in shortFruit)
    Console.WriteLine(fruit);

/* OUTPUT

Apple
Fig
Lemon
Mango

*/
4 April 2010