Thursday, January 26, 2012

Getting started with Lamba Expressions

C# 3.0 brought so much news (for example var, extensions ,LINQ, lambda expressions etc...).
Sometime companies have its reason to don't update .NET framework in their applications.
For this, developers who grow parallely to those applications, never have time to upgrade their knowledges.

I know companies that use 2003's IDE in 2011!

For those who never had a chance to see what's new in latest framework, like me, I dedicate this post.

What is a lambda expression and what can I do with it?

It's "an anonymous function that can contain expressions and statements, and can be used to create delegates or expression tree types" (msdn).
It also improves code legibility, let's see how to use that:

Lambda expressions rotates about "=>" operator that means "goes to".

So if I write "x => x+1" I mean that x (goes to) do x+1. Sounds easy.

A practice examples. How do you find an element in a IEnumerable Array which satisfies a condition?

Once we used foreach...
MyObject myIstance = null;

foreach(MyObject o in myArray)
We used Find method with an anonymous delegate as parameter..
MyObject myIstance = myArray.Find(delegate (MyObject o) { return o.Color=="#abcdef"; });
Today we can use Find method with lambda expressions...
MyObject myIstance = myArray.Find(o => o.Color=="#abcdef");
Which one can you read better? :)
Simply find in my array the object called o that satisfy that expression => o.Color="#abcdef".

Let's see other examples!
delegate int del(int i);
static void Main(string[] args)
    del myDelegate = x => x * x;
    int j = myDelegate(5); //j = 25
With the same syntax of before, I create a delegate that take x (int i) and multiplies itself;
If I call my delegate ,providing 5 as parameter, I expect the value 25 inside j. And so it is.

Imagine now that you have a IEnumerable object and want to apply to every child-object an action.
You can use lambda expressions combined with your imagination.

Create an extension that simply does it.
public static class Extensions
     public static void ForAll<t>(this IEnumerable<t> sequence, Action<t> action)
          foreach (T item in sequence)

Apply to everything you want! (that Implement IEnumerable interface)
//Create a string
StringBuilder builder = new StringBuilder();
pList.ForAll(x => build.AppendLine(x.FullName));


//Sum content
Int Count=0;
List<Type> typeContainer = GetTypeContainer;
typeContainer.ForAll(x => Count += DoAction(x, ref builder));
return Count;

Is it or not clear?

Remember that usually nice things are not the best things.
Lambda Expression are nice, clear and wow but they aren't ever the best choice.

I reccomend you this Stack Overflow discussion where you can prove what I've just write.

I end this post with an image that makes you think...

Hope this post helps someone, and if I don't convince you...  keep searching on web :)

No comments:

Post a Comment