Func, predicate and Action all are type of delegates, this was introduced with .net core version of c#, each delegates comes under System namespace, has some differences.
Learn what is delegate in c#, If you are new to c# programming.
Func<int, int> funcVariable = j => j = 5; // return integer, parameter integer
Predicate<int> isPositive = delegate (int val) { return val > 0; };
If you look at the definition of Func, Predicate and Action delegates, you will see the difference in return type and the parameters they accept; below are delegate declaration in system assembly.
public delegate TResult Func<in T, out TResult>(T arg);
public delegate bool Predicate<in T>(T obj); public delegate void Action<in T>(T obj);
// return string, parameter string
Func<string, string> selector = s => s.ToUpper();
public void testFunc()
{
Func<int, int, int, string> Addition = TotalValue;
string result = Addition(10, 20, 10);
Console.WriteLine($"Addition = {result}");
}
private static string TotalValue(int p1, int p2, int p3)
{
var o = p1 + p2 + p3;
return o.ToString();
}
the last datatype is the return type, here string in above code Func<int, int, int, string>.
Predicate returns boolean type only, can take multiple parameters
Predicate<int> predicateVariable = i => i > 0;
// return boolean value
var words = new List<string> { "green","field", "jungli", "hati", "flying", "birds"};
Predicate<string> has5Chars = word => word.Length == 5;
Console.WriteLine($"has5Chars - {has5Chars}");
var words2 = words.FindAll(has5Chars);
Console.WriteLine(string.Join(',', words2));
In above example predicate Predicate<string> has no parameter, return type is string.
public void testAction()
{
Action<int> Addition = TotalActionValue;
Addition(10);
}
private static void TotalActionValue(int i)
{
int o = 10;
}
Action delegate can be used when we don’t want any return value but some functionality to be executed with an event.