find and solve || findandsolve.com
Please wait.....

C# Predicate Delegate

The predicate is the delegate like Func and Action delegates in c# programming language. Delegate represents a method containing a set of criteria and checks whether the passed parameter meets those criteria. A predicate delegate method must take one input parameter and return a boolean like true or false.

The Predicate delegate is defined in the System namespace, like as given below

public delegate bool Predicate<in T>(T obj);


C# Predicate Delegate Example

In the given example of defining the Predicate delegate to hold the reference of one or more methods which is having the same method signature.

using System;
namespace FindAndSolve
{
   public class Program
   {
  static bool IsSmallCase(string str)
   {
    return str.Equals(str.ToUpper());
    }
public static void Main(string[] args)
 {
    Predicate<string> isSmall= IsSmallCase;
    bool result = isSmall("find and solve");
    Console.WriteLine(result);
   }
   }
}

Output

False


Predicate delegate with an anonymous method

In c# programming, you can assign the anonymous method directly to the Predicate delegate by using the delegate keyword as shown below.

using System;					

public class Program
{
 public static void Main()
 {
  Predicate<string> isUpper = delegate(string s) { return s.Equals(s.ToUpper());};
     bool result = isUpper("FIND AND SOLVE!");
  Console.Write(result);
 }
}

Output

True


C# Predicate Delegate with Lambda Expressions

In c#, we can also use Predicate delegate with lambda expressions. The lambda expressions are the shorthand way for declaring the anonymous methods.

using System;					

public class Program
{
 public static void Main()
 {
  Predicate<string> isSmall = x => x.Equals(x.ToLower());
     bool result = isSmall("find and solve");
  Console.Write(result);
 }
}

Output

True


C# Predicate Delegate Overview

  • In c# programaming language, Predicate is a built-in generic delegate, and it is useful to validate whether the input parameter meets the specified condition or not, and it’s the same as Func and Action delegates to hold the reference of one or more methods.
  • The Predicate delegate can hold only the methods that take only one input parameter and returns either true or false boolean type value.
  • While creating the predicate delegate, you must remember that you can include only one input parameter and the return type must be true or false.
  • You can use Predicate delegate in anonymous methods and lambda expressions.