Predicate Delegates in C#

后端 未结 10 1391
一个人的身影
一个人的身影 2020-11-27 09:13

Can you explain to me:

  • What is a Predicate Delegate?
  • Where should we use predicates?
  • Any best practices when using predicates?

10条回答
  •  [愿得一人]
    2020-11-27 09:31

    What is Predicate Delegate?

    1) Predicate is a feature that returns true or false.This concept has come in .net 2.0 framework. 2) It is being used with lambda expression (=>). It takes generic type as an argument. 3) It allows a predicate function to be defined and passed as a parameter to another function. 4) It is a special case of a Func, in that it takes only a single parameter and always returns a bool.

    In C# namespace:

    namespace System
    {   
        public delegate bool Predicate(T obj);
    }
    

    It is defined in the System namespace.

    Where should we use Predicate Delegate?

    We should use Predicate Delegate in the following cases:

    1) For searching items in a generic collection. e.g.

    var employeeDetails = employees.Where(o=>o.employeeId == 1237).FirstOrDefault();
    

    2) Basic example that shortens the code and returns true or false:

    Predicate isValueOne = x => x == 1;
    

    now, Call above predicate:

    Console.WriteLine(isValueOne.Invoke(1)); // -- returns true.
    

    3) An anonymous method can also be assigned to a Predicate delegate type as below:

    Predicate isUpper = delegate(string s) { return s.Equals(s.ToUpper());};
        bool result = isUpper("Hello Chap!!");
    

    Any best practices about predicates?

    Use Func, Lambda Expressions and Delegates instead of Predicates.

提交回复
热议问题