Saturday, 17 March 2012

C# : Predicate, Func, Action syntaxes

Bringing something out from my personal study material…

I have seen many people getting confused in C# Func, Predicate and Actions just because of the different syntactical ways of using them. Unfortunately, I am too not the exception.:-(

So I thought to bring all the styles at one place…

1.       Func
 Func performs some operation and returns something.

      Syntaxes:


List<string> FruitNames = new List<string>() { "Apple""Mango""Pinaple""Orange" };

//Func syntax 1: using lambada Expression
var func1 = FruitNames.Select((x) => x + " is sugary.");

//Func syntax 2: using anonymous function(delegate)
var func2 = FruitNames.Select(delegate(string x)
{
     return x + " is sugary.";
});

//Func syntax 3: using Func declaration with anonymous function(delegate)
var func3 = FruitNames.Select(new Func<stringstring>(delegate(string x)
{
     return x + " is sugary.";
}));




2.       Predicate
Predicate performs some operation and returns bool. It is nothing but Func always returning bool.

Syntaxes:


List<string> FruitNames = new List<string>() { "Apple""Mango""Pinaple""Orange" };

//Predicate syntax 1: using lambada Expression
var predicate1 = FruitNames.Find(x => x.ToLower().StartsWith("a"));

//Predicate syntax 2: using anonymous function(delegate)
var predicate2 = FruitNames.Find(delegate(string x)
{
     return x.ToLower().StartsWith("a");
});

//Predicate syntax 3: using Func declaration with anonymous function(delegate)
var predicate3 = FruitNames.Find(new Predicate<string>(delegate(string x)
{
     return x.ToLower().StartsWith("a");
}));



3.       Action
 Action performs some operation and returns nothing.

 Syntaxes:   


List<string> FruitNames = new List<string>() { "Apple""Mango""Pinaple""Orange" };


//Action syntax 1: using lambada Expression
FruitNames.ForEach((x) => Console.WriteLine(x + " is sugary."));

//Func syntax 2: using anonymous function(delegate)
FruitNames.ForEach(delegate(string x)
{
     Console.WriteLine(x + " is sugary.");
});

//Func syntax 3: using Func declaration with anonymous function(delegate)
FruitNames.ForEach(new Action<string>(delegate(string x)
{
     Console.WriteLine(x + " is sugary.");
}));




So…go and use them…they do wonders to the code….

As a SharePoint Professional, I sometimes feel little low because SharePoint’s future lies in OOB approach with very little coding opportunities. :-( Very interesting to see how fast C# language is getting evolved with every new .net framework release where .net framework itself getting richer and richer...Need enough time, patience, focus and motivation to explore those. I should keep on trying with my little brain....

No comments:

Post a Comment