C#: Predicate Delegates in C#

http://stackoverflow.com/questions/556425/predicate-delegates-in-c

Predicate Delegates in C#

Can you explain me;

  • What is Predicate Delegate ?
  • Where should we use predicates ?
  • Any best practices about predicates ?

Descriptive source code will be appreciated,

Soln:

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); } } 
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s