Func Predicate Action Delegate in c# examples

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; };
func and predicate in c#

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.

  • Func Delegate
    public delegate TResult Func<in T, out TResult>(T arg);
    Return Type: TResult (returns object)
    Parameters: 0 to 16
  • Predicate Delegate
    public delegate bool Predicate<in T>(T obj);
    Return Type: bool
    Parameters: 1 to 1
  • Action Delegate
    public delegate void Action<in T>(T obj);
    Return Type: void
    Parameters: 0 to 16
C# Func Delegate example
Func Encapsulates a method that accepts 0 to 16 parameters and returns a value of type specified by the TResult parameter, return anything other than void, can be int, string, object etc.
// 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>.

C# Predicate Delegate example
Predicate represents the method that defines a set of criteria and determines whether the specified object meets those criteria, return Boolean value.

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.

Action delegate in c#
Action Encapsulates a method that can take multiple parameters and does not return a value, this is void type.
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.

 
func predicate action delegate
.Net C# Programming Tutorials
Online Tutorials
C# .net Interview Questions Answers
.Net C# Examples | Join .Net C# Course