C# Func
last modified November 6, 2026
In this article we show how to use the Func delegate in C#.
A delegate is a type that represents a reference to a method with a particular signature. A delegate variable can hold a method, an anonymous method, or a lambda expression, and invoking the variable calls the function. This lets us pass functions as arguments, store them, and return them from methods.
Func is a family of built-in generic delegates for functions
that return a value. There are 17 of them, from Func<TResult>
with no parameters to a version with 16 parameters. The last type argument is
always the return type.
public delegate TResult Func<in T1, in T2, out TResult>(T1 arg1, T2 arg2);
This is the Func with two parameters. The related
Action delegates represent functions without a return value, and
Predicate<T> a function that returns bool.
A simple Func
The first example assigns a method to a Func variable.
string GetMessage()
{
return "Hello there!";
}
Func<string> sayHello = GetMessage;
Console.WriteLine(sayHello());
GetMessage takes no parameters and returns a string, which
matches Func<string>.
Func<string> sayHello = GetMessage;
We assign the method name without parentheses. This is a method group conversion: the delegate refers to the method, which is not called yet.
Console.WriteLine(sayHello());
Invoking the delegate calls GetMessage.
$ dotnet run Hello there!
Func with parameters
The type arguments of Func list the parameter types followed by
the return type.
int Sum2(int x, int y) => x + y;
int Sum3(int x, int y, int z) => x + y + z;
Func<int, int, int> add2 = Sum2;
Func<int, int, int, int> add3 = Sum3;
Console.WriteLine(add2(150, 10));
Console.WriteLine(add3(150, 20, 30));
Func<string, string> upper = s => s.ToUpper();
Func<double, double> sqrt = Math.Sqrt;
Console.WriteLine(upper("falcon"));
Console.WriteLine(sqrt(81));
Func<int, int, int> takes two integers and returns an
integer; Func<int, int, int, int> takes three.
Func<double, double> sqrt = Math.Sqrt;
Any method with a matching signature can be assigned, including methods of
the framework. Math.Sqrt has a double parameter and
a double result.
$ dotnet run 160 200 FALCON 9
Func and custom delegates
Before the generic delegates existed, we had to declare a delegate type for each signature.
int Sum(int x, int y)
{
return x + y;
}
Add addTwo = Sum;
Func<int, int, int> addFunc = Sum;
Console.WriteLine(addTwo(150, 10));
Console.WriteLine(addFunc(150, 10));
delegate int Add(int x, int y);
The Add delegate has the same signature as
Func<int, int, int>, and both can hold the
Sum method.
delegate int Add(int x, int y);
A custom delegate gives the parameters meaningful names and the type a
descriptive name. Func saves the declaration and is the type that
LINQ and most libraries expect. Note that the two types are not
interchangeable: an Add cannot be assigned to a
Func<int, int, int> variable.
$ dotnet run 160 160
Func with lambda expressions
Lambda expressions create Func delegates without a named method.
Func<int, int, int> max = (a, b) => a > b ? a : b;
Console.WriteLine(max(4, 9));
Func<double, double, double> hypot = (a, b) => Math.Sqrt(a * a + b * b);
Console.WriteLine(hypot(3, 4));
Func<string, string> initials = name =>
{
var parts = name.Split(' ', StringSplitOptions.RemoveEmptyEntries);
return string.Concat(parts.Select(p => char.ToUpper(p[0])));
};
Console.WriteLine(initials("john ronald reuel tolkien"));
var twice = (int x) => x * 2;
Console.WriteLine(twice.GetType().Name);
The parameter types of the lambdas come from the Func type on the
left side.
Func<string, string> initials = name =>
{
A lambda with a block body can contain several statements and returns its
value with return.
var twice = (int x) => x * 2;
A lambda with typed parameters can be assigned to var. The
compiler gives it a natural type, here Func<int, int>,
which the runtime prints as Func`2: the generic type with two
type arguments.
$ dotnet run 9 5 JRRT Func`2
Func in LINQ
Many LINQ methods take Func delegates. Where takes a
Func<T, bool> that decides which elements to keep.
Func<string, bool> hasThree = str => str.Length == 3;
string[] words =
[
"sky", "forest", "wood", "cloud", "falcon", "owl", "ocean",
"water", "bow", "tiny", "arc"
];
IEnumerable<string> threeLetterWords = words.Where(hasThree);
foreach (var word in threeLetterWords)
{
Console.WriteLine(word);
}
The example selects words with three letters.
Func<string, bool> hasThree = str => str.Length == 3;
The lambda returns true for strings of length three.
IEnumerable<string> threeLetterWords = words.Where(hasThree);
Where calls the delegate for each word.
$ dotnet run sky owl bow arc
Collections of functions
Delegates are values, so they can be stored in lists and dictionaries.
int[] vals = [1, 2, 3, 4, 5];
Func<int, int> square = x => x * x;
Func<int, int> cube = x => x * x * x;
Func<int, int> inc = x => x + 1;
List<Func<int, int>> fns = [inc, square, cube];
foreach (var fn in fns)
{
var res = vals.Select(fn);
Console.WriteLine(string.Join(", ", res));
}
var named = new Dictionary<string, Func<double, double, double>>
{
["+"] = (a, b) => a + b,
["-"] = (a, b) => a - b,
["*"] = (a, b) => a * b,
["/"] = (a, b) => a / b,
};
foreach (var (op, fn) in named)
{
Console.WriteLine($"12 {op} 4 = {fn(12, 4)}");
}
We apply three functions from a list to an array.
var named = new Dictionary<string, Func<double, double, double>>
A dictionary maps operator symbols to functions. This is a simple way to
replace a long switch in a calculator.
$ dotnet run 2, 3, 4, 5, 6 1, 4, 9, 16, 25 1, 8, 27, 64, 125 12 + 4 = 16 12 - 4 = 8 12 * 4 = 48 12 / 4 = 3
Filtering records
A Func predicate can capture variables from the surrounding
code.
User[] users =
[
new(1, "John", "London", new DateOnly(2001, 4, 1)),
new(2, "Lenny", "New York", new DateOnly(1997, 12, 11)),
new(3, "Andrew", "Boston", new DateOnly(1987, 2, 22)),
new(4, "Peter", "Prague", new DateOnly(1936, 3, 24)),
new(5, "Anna", "Bratislava", new DateOnly(1973, 11, 18)),
new(6, "Albert", "Bratislava", new DateOnly(1940, 12, 11)),
new(7, "Adam", "Trnava", new DateOnly(1983, 12, 1)),
new(8, "Robert", "Bratislava", new DateOnly(1935, 5, 15)),
new(9, "Robert", "Prague", new DateOnly(1998, 3, 14)),
];
var city = "Bratislava";
Func<User, bool> livesIn = e => e.City == city;
foreach (var e in users.Where(livesIn))
{
Console.WriteLine(e);
}
record User(int Id, string Name, string City, DateOnly Born);
The program selects users who live in Bratislava.
var city = "Bratislava"; Func<User, bool> livesIn = e => e.City == city;
The lambda uses the city variable. It is captured by reference:
if we changed city before running the query, the new value would
be used.
$ dotnet run
User { Id = 5, Name = Anna, City = Bratislava, Born = 11/18/1973 }
User { Id = 6, Name = Albert, City = Bratislava, Born = 12/11/1940 }
User { Id = 8, Name = Robert, City = Bratislava, Born = 5/15/1935 }
Combining functions
One Func can call another.
User[] users =
[
new(1, "John", "London", new DateOnly(2001, 4, 1)),
new(2, "Lenny", "New York", new DateOnly(1997, 12, 11)),
new(3, "Andrew", "Boston", new DateOnly(1987, 2, 22)),
new(4, "Peter", "Prague", new DateOnly(1936, 3, 24)),
new(5, "Anna", "Bratislava", new DateOnly(1973, 11, 18)),
new(6, "Albert", "Bratislava", new DateOnly(1940, 12, 11)),
new(7, "Adam", "Trnava", new DateOnly(1983, 12, 1)),
new(8, "Robert", "Bratislava", new DateOnly(1935, 5, 15)),
new(9, "Robert", "Prague", new DateOnly(1998, 3, 14)),
];
var today = new DateOnly(2026, 11, 6);
var age = 60;
Func<User, int> getAge = u =>
today.Year - u.Born.Year - (today < u.Born.AddYears(today.Year - u.Born.Year) ? 1 : 0);
Func<User, bool> olderThan = u => getAge(u) > age;
foreach (var u in users.Where(olderThan))
{
Console.WriteLine($"{u.Name} ({getAge(u)})");
}
record User(int Id, string Name, string City, DateOnly Born);
The program selects users older than 60 years. The reference date is fixed so that the output does not change over time.
Func<User, int> getAge = u =>
today.Year - u.Born.Year - (today < u.Born.AddYears(today.Year - u.Born.Year) ? 1 : 0);
getAge computes the age in whole years. We subtract one if the
birthday has not yet occurred this year.
Func<User, bool> olderThan = u => getAge(u) > age;
The predicate calls getAge and compares the result.
$ dotnet run Peter (90) Albert (85) Robert (91)
Func and Predicate
Predicate<T> and Func<T, bool> have the
same signature, but they are different types. The older
Array and List methods, such as
FindAll, take a Predicate; LINQ takes a
Func.
int[] vals = [-1, 3, 8, 0, -5, 12];
Predicate<int> isPositive = e => e > 0;
Func<int, bool> isPositiveFunc = e => e > 0;
int[] a = Array.FindAll(vals, isPositive);
var b = vals.Where(isPositiveFunc);
Console.WriteLine(string.Join(" ", a));
Console.WriteLine(string.Join(" ", b));
var c = vals.Where(isPositive.Invoke);
Console.WriteLine(string.Join(" ", c));
Predicate<int> converted = new(isPositiveFunc);
Console.WriteLine(Array.FindIndex(vals, converted));
We filter the same array with both kinds of delegates.
var c = vals.Where(isPositive.Invoke);
A Predicate cannot be passed to Where directly. Its
Invoke method, however, is a method group that converts to a
Func.
Predicate<int> converted = new(isPositiveFunc);
The other way, we create a Predicate from the Func.
FindIndex then finds the first positive value at index 1.
$ dotnet run 3 8 12 3 8 12 3 8 12 1
Func as a parameter
Our own methods can take Func parameters to let the caller
decide part of their behaviour.
List<Person> data =
[
new("John Doe", "gardener"),
new("Robert Brown", "programmer"),
new("Lucia Smith", "teacher"),
new("Thomas Neuwirth", "teacher")
];
ShowOutput(data, r => r.Occupation == "teacher");
Console.WriteLine("---");
ShowOutput(data, r => r.Name.StartsWith('R'));
void ShowOutput(List<Person> list, Func<Person, bool> condition)
{
foreach (var person in list.Where(condition))
{
Console.WriteLine($"{person.Name}, {person.Occupation}");
}
}
record Person(string Name, string Occupation);
ShowOutput prints the people that satisfy a condition supplied
by the caller.
void ShowOutput(List<Person> list, Func<Person, bool> condition)
We call it twice with different lambdas.
$ dotnet run Lucia Smith, teacher Thomas Neuwirth, teacher --- Robert Brown, programmer
Composing functions
Functions can be applied in sequence, or combined into a new function.
int[] vals = [1, 2, 3, 4, 5];
Func<int, int> inc = e => e + 1;
Func<int, int> cube = e => e * e * e;
var res = vals.Select(inc).Select(cube);
Console.WriteLine(string.Join(" ", res));
Func<int, int> incThenCube = Compose(inc, cube);
Func<int, int> cubeThenInc = Compose(cube, inc);
Console.WriteLine(string.Join(" ", vals.Select(incThenCube)));
Console.WriteLine(string.Join(" ", vals.Select(cubeThenInc)));
static Func<T, TResult> Compose<T, TMid, TResult>(Func<T, TMid> first, Func<TMid, TResult> second) =>
x => second(first(x));
Chaining two Select calls first increments each value and then
cubes it.
static Func<T, TResult> Compose<T, TMid, TResult>(Func<T, TMid> first, Func<TMid, TResult> second) =>
x => second(first(x));
Compose takes two functions and returns a new one that calls
them in order. The order matters: incrementing and then cubing gives
different results than cubing and then incrementing.
$ dotnet run 8 27 64 125 216 8 27 64 125 216 2 9 28 65 126
Returning functions
A method can create and return a Func. The returned lambda keeps
access to the variables it captured.
Func<int, int> add5 = MakeAdder(5);
Func<int, int> add10 = MakeAdder(10);
Console.WriteLine(add5(1));
Console.WriteLine(add10(1));
Func<int> counter = MakeCounter();
Console.WriteLine(counter());
Console.WriteLine(counter());
Console.WriteLine(counter());
static Func<int, int> MakeAdder(int n) => x => x + n;
static Func<int> MakeCounter()
{
int count = 0;
return () => ++count;
}
MakeAdder returns a function that adds a fixed number.
static Func<int> MakeCounter()
{
int count = 0;
return () => ++count;
}
The local variable count outlives the method because the lambda
captured it. Such a lambda with its captured state is called a closure. Each
call of the counter increments the same variable.
$ dotnet run 6 11 1 2 3
Asynchronous Func
An asynchronous lambda returning a value has a type of the form
Func<..., Task<T>>.
Func<string, Task<int>> countWordsAsync = async path =>
{
string text = await File.ReadAllTextAsync(path);
return text.Split((char[]) [' ', '\n'], StringSplitOptions.RemoveEmptyEntries).Length;
};
await File.WriteAllTextAsync("words.txt", "an old falcon\nsat on a rock\n");
int count = await countWordsAsync("words.txt");
Console.WriteLine($"Words: {count}");
File.Delete("words.txt");
The delegate reads a file asynchronously and counts its words.
Func<string, Task<int>> countWordsAsync = async path =>
The lambda takes a path and returns a Task<int>. Invoking
the delegate starts the work, and await gets the result.
$ dotnet run Words: 7
Choosing a function at run time
Because functions are values, a conditional expression can choose one.
string[] words = ["apple", "banana", "cherry", "date", "fig", "elderberry"];
foreach (var filterType in new[] { "long", "short" })
{
Func<string, bool> filter = filterType == "long"
? s => s.Length > 5
: s => s.Length <= 5;
Console.WriteLine($"{filterType}: {string.Join(", ", words.Where(filter))}");
}
Depending on filterType, the filter selects long or short
words.
Func<string, bool> filter = filterType == "long"
? s => s.Length > 5
: s => s.Length <= 5;
Both branches of the conditional are lambdas. The target type
Func<string, bool> tells the compiler their type.
$ dotnet run long: banana, cherry, elderberry short: apple, date, fig
Lazy evaluation
A Func passed to LINQ is not called when the query is created,
but when its results are enumerated.
Func<string, int?> parseNumber = s =>
{
Console.WriteLine($"parsing '{s}'");
return int.TryParse(s, out int n) ? n : null;
};
string[] inputs = ["123", "abc", "456"];
var results = inputs.Select(parseNumber);
Console.WriteLine("query created");
foreach (var result in results)
{
Console.WriteLine(result is int n ? $"Result: {n}" : "Result: invalid");
}
parseNumber prints a message when it is called and returns
null for invalid input.
Console.WriteLine("query created");
The output shows that nothing is parsed before the loop starts, and that each value is parsed just before it is printed. If the query were enumerated twice, the function would run twice for each element.
$ dotnet run query created parsing '123' Result: 123 parsing 'abc' Result: invalid parsing '456' Result: 456
Source
In this article we have worked with the Func delegate in C#.
Author
List all C# tutorials.