Canavar Canavar - 2 months ago 18
C# Question

Predicate Delegates in C#

Can you explain to me;


  • What is a Predicate Delegate?

  • Where should we use predicates?

  • Any best practices when using predicates?



Descriptive source code will be appreciated,

Thanks for all replies!

Answer

A predicate is a function that returns true or false. A predicate delegate is a reference to a predicate.

So basically a predicate delegate is a reference to a function that returns true or false. Predicates are very useful for filtering a list of values - here is an example.

using System;
using System.Collections.Generic;

class Program
{
    static void Main()
    {
    	List<int> list = new List<int> { 1, 2, 3 };

    	Predicate<int> predicate = new Predicate<int>(greaterThanTwo);

    	List<int> newList = list.FindAll(predicate);
    }

    static bool greaterThanTwo(int arg)
    {
    	return arg > 2;
    }
}

Now if you are using C# 3 you can use a lambda to represent the predicate in a cleaner fashion:

using System;
using System.Collections.Generic;

class Program
{
    static void Main()
    {
    	List<int> list = new List<int> { 1, 2, 3 };

    	List<int> newList = list.FindAll(i => i > 2);
    }
}
Comments