Introduction
Func and Action are two generic delegate types that are built into C#, so you usually don't need to explicitly define custom delegates.
A generic delegate called Func is part of the System namespace. It has one out parameter and zero or more input parameters. As an out parameter, the final one is regarded as such.
As can be seen below, the Func delegate that accepts a single input parameter and a single output parameter is defined in the System namespace.
Syntax
modifier delegate returnType Func<datatype parameter, out returnType>(T args);
As an illustration,
public delegate TResult Func<in T, out TResult>(T arg);
The remaining parameters are regarded as input parameter types, and the final parameter enclosed in angle brackets <> is regarded as the return type.
The representation below shows a Func delegate with two input parameters and one out parameter.
As an illustration,
public delegate TResult Func<in T1, in T2, out TResult>(T1 arg1, T2 arg2);
The subsequent Func delegate accepts two int-type input parameters and outputs an int-type value:
Func<int, int, int> sum;
The function delegate mentioned above can have any method assigned to it that accepts two int parameters and returns an int value.
static int Sum(int a, int b)
{
return a + b;
}
Func<int, int, int> add = Sum;
int result = add(11, 34);
Console.WriteLine("{0} - {1}", nameof(result), result);
0 to 16 different types of input parameters can be included in a Func delegate type. For the outcome, it needs to have an out parameter, though. For instance, the Func delegate that follows only has an out parameter and no input parameters.
Func<int> customFunction;
C# Functions using an anonymous approach
Using the delegate keyword, you can give the Func delegate an anonymous method.
Func<int> customRandomFunc = delegate ()
{
Random random = new Random();
return random.Next(1, 1000);
};
Console.WriteLine("{0} - {1}", nameof(customRandomFunc), customRandomFunc());
Console.WriteLine("\n{0} - {1}", nameof(customRandomFunc), customRandomFunc());
Console.WriteLine("\n{0} - {1}", nameof(customRandomFunc), customRandomFunc());
Use Lambda Expression to function
It is also possible to use a lambda expression with a Func delegate, as demonstrated below.
Func<int> customRandomFunc = () => new Random().Next(1, 1000);
Func<int, int, int> Sum = (a, b) => a + b;
var randomNumber = customRandomFunc();
Console.WriteLine("{0} - {1}", nameof(randomNumber), randomNumber);
var add = Sum(51, 11);
Console.WriteLine("\n{0} - {1}", nameof(add), add);
Crucial points to keep in mind
- Func is an inbuilt type of delegate.
- The type of func delegate must return a value.
- Input parameters for a func delegate type can range from 0 to 16.
- Ref and out parameters are not allowed by the func delegate.
- You can use a lambda expression or anonymous method with the func delegate type.
We learned the new technique and evolved together.
Happy coding!