Saturday, September 8, 2012

Predicate delegate in C#

I am writing few post on different type of delegates and this post also will be part of it. In this post I am going to write about Predicate delegate which is available from C# 2.0. Following is list of post that I have written about delegates.

  1. Delegates in C#.
  2. Multicast delegates in C#.
  3. Func delegate in C#.
  4. Action delegate in C#.

Predicate delegate in C#:

As per MSDN predicate delegate is a pointer to a function that returns true or false and takes generics types as argument. It contains following signature.

Predicate<T> – where T is any generic type and this delegate will always return Boolean value. The most common use of a predicate delegate is to searching items in array or list. So let’s take a simple example. Following is code for that.


using System;
using System.Collections.Generic;

namespace DelegateExample
{
    class Program
    {
        static void Main(string[] args)
        {
            Predicate<int> numberGreaterthenFive = i => i > 5;
            List<int> NumberList = new List<int>{1,2,3,4,5,6,7,8,9,10};
            var newlist = NumberList.FindAll(numberGreaterthenFive);
            Action<int> print = i => Console.WriteLine(i);
            newlist.ForEach(print);
        }
    }
}

If you see in the above code I have written a predicate delegate numberGreaterthenFive to decide whether numebr is greater then five or not. Then I have created a list of number and use the predicate delegate which we created just before find that number is greater then five or not. So once we get new list, I have printed the number with console writeline and action delegate.

Let’s run the application and following is output as expected.

Predicate Delegate in C#- Delegate Series

Hope you like it. Stay tuned for more updates!!

Shout it

kick it on DotNetKicks.com
Share:

1 comment:

Your feedback is very important to me. Please provide your feedback via putting comments.

Search This Blog
Loading...
About Me
My Photo

Full Stack Developer,Blogger,Microsoft Mvp, Mentor, Life long learner, 10+ Years of Experience for JavaScript, web and Microsoft technologies. ASP.NET MVC,Web Forms,C#,AngularJs,Golang
Mvp profile
Subscribe to my blog

Enter your email address:

Follow us on facebook
Blog Archive
Total Pageviews