Tip #110 explored the Action delegate that may be used to encapsulate a delegate method that does not accept parameters and does not have a return value. Today we are going to check the Func<TResult> delegate and its overloads to have more flexibility on using delegates with methods that return value and / or accept parameters.
Overloads
The following overloads are available:
- It does not accept parameters but returns a value;
public delegate TResult Func<TResult>();
- It accepts one parameter and returns a value;
public delegate TResult Func<T, TResult>(T arg);
- It accepts two parameters and returns a value;
public delegate TResult Func<T1, T2, TResult>(T1 arg1, T2 arg2);
- It accepts three parameters and returns a value;
public delegate TResult Func<T1, T2, T3, TResult>(T1 arg1, T2 arg2, T3 arg3);
- It accepts four parameters and returns a value.
public delegate TResult Func<T1, T2, T3, T4, TResult>(T1 arg1, T2 arg2, T3 arg3, T4 arg4);
How to…
The following example shows a call to a method that retrieves a Boolean value:
private bool M()
{
return false;
}
[…]
Func<bool> myDelegate = M;
if (myDelegate())
Console.WriteLine(“Return value is true.”);
else
Console.WriteLine(“Return value is false.”);
The next code snippet shows a call to a method that accepts two decimal numbers as input and returns a decimal number that represents the sum of both input parameters:
private decimal Sum(decimal n1, decimal n2)
{
return n1 + n2;
}
Func<decimal, decimal, decimal> mySum = Sum;
Console.WriteLine(mySum(99.99M, 12.21M));
Anonymous methods and lambda expressions
You may use anonymous methods or lambda expressions in conjunction with the Func<> delegate.
- Anonymous method:
Func<decimal, decimal, decimal> mySum = delegate(decimal n1, decimal n2) { return n1 + n2; };
Console.WriteLine(mySum(99.99M, 12.21M));
- Lambda expression:
Func<decimal, decimal, decimal> mySum = (decimal n1, decimal n2) => n1 + n2;
Console.WriteLine(mySum(99.99M, 12.21M));
Leave a comment