C# 3.0 includes built-in generic delegate types Func, so that you don't need to define our own custom delegates.
Func is a generic delegate included in the System namespace. It has zero or more than one input parameters and one out parameter. The last parameter is an out parameter.
public delegate TResult Func<in T, out TResult>(T arg);
The last parameter in the angle brackets <> is the return type and remaining
parameter is input parameter type.
We can assign any method to the func delegate that takes two int parameters and returns an int value.
Now, we take Func delegate instead of some Operation delegate in the first example.
static int Sum(int x, int y)
static void Main(string args)
Func<int,int, int> add = Sum;
int result = add(10, 10);
A Func delegate type can include 0 to 16 input parameters of different types. However, it must include one out parameter for return type. For example, the following func delegate doesn't have any input parameter, it includes only a out parameter.
Func<int> getRandomNumber = delegate()
Random rnd = new Random();
Func with Lambda Expression
A Func delegate can also be used with a lambda expression, as shown below:
Func<int> getRandomNumber = () => new Random().Next(1, 100);
Advantages of Func Delegates
- Easy and quick to define delegates.
- Makes code short.
- Compatible type throughout the application.
Things to be remember when using Func :
- Func is built-in delegate type.
- Func delegate type must return a value.
- Func delegate type can have zero to 16 input parameters.
- Func delegate does not allow ref and out parameters.
- Func delegate type can be used with an anonymous method or lambda expression.