Explanation of Func

zSynopsis picture zSynopsis · May 18, 2009 · Viewed 64.9k times · Source

I was wondering if someone could explain what Func<int, string> is and how it is used with some clear examples.

Answer

Jon Skeet picture Jon Skeet · May 18, 2009

Are you familiar with delegates in general? I have a page about delegates and events which may help if not, although it's more geared towards explaining the differences between the two.

Func<T, TResult> is just a generic delegate - work out what it means in any particular situation by replacing the type parameters (T and TResult) with the corresponding type arguments (int and string) in the declaration. I've also renamed it to avoid confusion:

string ExpandedFunc(int x)

In other words, Func<int, string> is a delegate which represents a function taking an int argument and returning a string.

Func<T, TResult> is often used in LINQ, both for projections and predicates (in the latter case, TResult is always bool). For example, you could use a Func<int, string> to project a sequence of integers into a sequence of strings. Lambda expressions are usually used in LINQ to create the relevant delegates:

Func<int, string> projection = x => "Value=" + x;
int[] values = { 3, 7, 10 };
var strings = values.Select(projection);

foreach (string s in strings)
{
    Console.WriteLine(s);
}

Result:

Value=3
Value=7
Value=10