Thursday, January 15

Lambda Expressions in C# 3.0

Lambda Expression is a new feature introduced in C# 3.0. Lambda Expressions provide a more concise, functional syntax for writing anonymous methods. Lambda expressions can be used when calling a method that takes a delegate as a parameter. Instead of writing a method, creating a delegate from the method, and passing the delegate to the method as a parameter, simply writes a lambda expression in-line as a parameter to the method. Lambda expression can be written as a parameter list followed by the "=>" token, followed by an expression or a statement block.

parameters => expression

For example:

x => x2 which tells that the function takes x as the input parameter and returns x2.

If the type of the parameter is specified, or if the expression has more than one parameter (be their type indicated explicitly or not) parenthesis are mandatory. For example:

(x, y) => x * y;

Consider a simple anonymous delegate.

simpledelegate del = new simpledelegate(delegate (int a)
{
return a * 2;
});

It can be written by using lambda expression as follows

simpledelegate del = a => a * 2;

C# 3.0 defines the number of generic delegates that can be assigned to the lambda expression instead of var keyword which infers the type. Let's take a look at an example of using a few of those generic delegates:



In the above example, there are different extension methods such as Where, OrderBy and Select. The Where extension method takes a generic delegate with int parameter and a return type of boolean to identity if a certain element be included in the output sequence. Similarly Select extension method takes an int parameter and returns an int, but it could return anything that you want the result to be transformed into. In the OrderBy extension method, the input is int parameter and using it to identify if it is even or odd. Based on that, the results are sorted. With the introduction of generic delegate in C# 3.0, it is fairly non trivial to assign our lambda expressions to generic delegates and pass those delegates to the extension methods. Generic delegates allow to define up to 4 parameters and 1 return type so it is possible to have a delegates like this:



If the method or delegate does not meet the criteria then delegate that takes those parameters can be declared manually.. Generic delegate usually cover majority of scenarios but in cases where it does not meet the needs, feel free to write a custom delegate.

Unlike anonymous methods, which require parameter type declarations to be explicitly stated, Lambda expressions permit parameter types to be omitted and instead allow them to be inferred based on the usage i.e. the parameters of a lambda expression can be explicitly or implicitly typed. In an explicitly typed parameter list, the type of each expression is explicitly specified. In an implicitly typed parameter list, the types are inferred from the context in which the lambda expression occurs:

(int x) => x + 1 // explicitly typed parameter
y => return y * y; // implicitly typed parameter

There are cases where type inference may not return the data type that we really want the lambda expression to return. In those cases, it is better to explicitly specify the parameter type on the lambda expression.

For example:



This will give compile time error because implicit return type of this expression will be double but the expected one is int. So type casting is required.



Sample Program 1:

Simple program to display all the numbers greater than 5 from the array:

class Program
{
static void Main(string[] args)
{
int[] intarray = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 0 };
foreach (int i in intarray.Where(x => x>5))
// finds out all the items in the array greater than 5
{
Console.WriteLine(i);
}
Console.ReadKey();
}
}

Output:

6
7
8
9

Here Where () extension method above is passed a filter parameter of type Func, which is a delegate that takes a method with a single parameter of type "T" and returns a Boolean indicating whether a condition is met. When lambda expression is passed as an argument to this Where () extension method, the C# compiler will compile the lambda expressions to be an IL method delegate (where the type will be int) and evaluate whether a given condition is met.

Lambda expressions are basically of two types. One is considered a simple expression where everything is inferred and consists of an expression only. The second type of lambda expression is statement blocks which are composed of braces and return type.



The first lambda expression is considered a simple expression which does not have a statement body because there is no return statement and braces whereas the second lambda statement includes a statement body because it has a return statement and braces. Although both get compiled to a delegate, the benefit of lambda expressions without a statement body is that it can be converted to an expression tree which a certain provider can use to generate its own implementation. This is much like LINQ to SQL will convert the expression tree to its domain specific language called SQL, and send it to the database.

It is possible to create expression tree directly without using lambda expressions. An example of creating expression tree for a lambda expression, square = x => x * x is shown below:

Sample Program 2:

Expression tree for square = x => x * x:



Output:

1
4
9
16

Closure in lambda expression:

Closure is a concept that comes from functional programming. It means that lambda expression can use the variable which is outside the scope of the lambda expression and such variables are known as captured variables or outside variables. In the background, C# compiler takes all those captured variables and puts them in a generated class. When the lambda expressions are used with outside variables, they are not picked up by the garbage collector, and are forced to hang around until they are used by the lambda expressions or the expression goes out of scope.

Sample Program 3:



Output:

Result is:6

In the above example, the variable, multiplier is used inside the lambda expression although it is declared outside the scope of the expression. This concept is called variable capture.

Parameter restrictions of lambda expression:

1) There are certain restrictions of using a lambda expression with ref or out parameter. When a variable is passed with ref or out keyword, the parameter type should be explicitly specified because the compiler cannot infer the type of the variable.

Sample Program 4:

Sample program with a lambda expression having out parameter:

class closure
{
delegate void outparameterdel(out int i);
public static void Main()
{
int i;
// compilation error if type is not specified explicitly

outparameterdel del = (out int a) => a = 5;
del(out i);
Console.WriteLine(("Result is: "+i);
Console.ReadKey();
}
}

Output:

Result is:5

2) Another restriction is that we cannot use the params keyword in the parameter type for a lambda expression regardless of whether or not the type of the parameter is explicitly specified.

Conclusion:

I have explained about one of C# 3.0 feature, lambda expressions and how the anonymous delegates can be converted to lambda expressions, how it differs, parameter restrictions etc.

22 comments:

Anonymous said...

I pay a visit each day a few web sites and information sites
to read content, however this website offers feature based
content.

Also visit my web-site :: More info

Anonymous said...

I have fun with, result in I found just what I used to be taking a look for.
You have ended my 4 day lengthy hunt! God Bless you man.
Have a great day. Bye

Also visit my homepage ... Infromtion site

Anonymous said...

My developer is trying to convince me to move to .net from PHP.

I have always disliked the idea because of the costs. But he's tryiong none the less. I've been using Movable-type on numerous websites for about a
year and am worried about switching to another platform.

I have heard very good things about blogengine.net. Is there a way I can import all my wordpress posts into it?
Any help would be greatly appreciated!

My web blog: website

Anonymous said...

You really make it appear so easy along with your presentation but I in finding
this matter to be actually something which I think I would never understand.

It kind of feels too complex and extremely wide for me.
I am having a look ahead to your next submit, I will attempt to
get the cling of it!

Also visit my page ... visit url

Anonymous said...

Hmm is anyone else encountering problems with the pictures on
this blog loading? I'm trying to figure out if its a problem on my end or if it's the
blog. Any feedback would be greatly appreciated.


Feel free to surf to my website; Office furniture Suppliers

Anonymous said...

It's actually a great and useful piece of information. I'm
glad that you simply shared this helpful information with us.
Please keep us informed like this. Thanks for sharing.



Visit my webpage business of architecture

Anonymous said...

Great information. Lucky me I came across your
site by accident (stumbleupon). I've saved it for later!

My site - IT consulting Johannesburg

Anonymous said...

Good post! We will be linking to this particularly
great content on our website. Keep up the good writing.


Also visit my web-site ... Infromtion site

Anonymous said...

''Wow But farmacia on line does not work, he added.

Here is my page; Why not Try These out

Anonymous said...

If a twenty eight-year-old pitcher's pituitary gland produces large quantities of farmacia on line in the pockets of fighters?

my web site - go to these guys

Anonymous said...

Counterfeit farmacia on line may be the only treatment.

The viewers are frustrated, but given all this real estate, the smaller,
bite-sized egos instead of the whole package seem tighter and denser.
I assumed they were European visitors. Call reception was good, but can be saved to your phone as well.


My web blog pagerankkontrol.com

Anonymous said...

Thanks for the marvelous posting! I certainly enjoyed reading it, you can be a great author.
I will ensure that I bookmark your blog and definitely will come back down the road.
I want to encourage you to continue your great writing, have a nice morning!


Here is my blog post - click this site

Anonymous said...

I read this paragraph completely about the comparison of most recent and previous technologies,
it's amazing article.

my page more info

Anonymous said...

I drop a comment each time I appreciate a article on
a website or I have something to valuable to contribute to the discussion.
Usually it's caused by the sincerness displayed in the article I looked at. And after this article "Lambda Expressions in C# 3.0". I was excited enough to drop a comment ;-) I do have some questions for you if you do not mind. Is it just me or do a few of the comments look as if they are coming from brain dead people? :-P And, if you are writing at additional sites, I would like to keep up with anything new you have to post. Would you list all of your communal sites like your twitter feed, Facebook page or linkedin profile?

Review my blog post :: Click Here

Anonymous said...

whoah this weblog is fantastic i really like reading
your articles. Keep up the great work! You realize, lots of persons
are hunting around for this info, you could help them greatly.



Also visit my blog post - Visit here

Anonymous said...

My partner and I stumbled over here coming from a different web page and thought I should check things out.

I like what I see so now i am following you. Look forward to looking at your web page for
a second time.

Here is my page :: visit this site

Anonymous said...

Hello, I enjoy reading through your article post.

I wanted to write a little comment to support you.

Feel free to visit my weblog :: more info

Anonymous said...

hey there and thank you for your information – I have
definitely picked up something new from right here.
I did however expertise several technical points using this site, as I experienced to reload the web site many times previous to I could
get it to load correctly. I had been wondering if
your web hosting is OK? Not that I am complaining,
but slow loading instances times will very frequently affect your placement in google and
can damage your quality score if advertising and marketing with Adwords.
Anyway I'm adding this RSS to my e-mail and could look out for a lot more of your respective interesting content. Make sure you update this again soon.

My page; more info

Anonymous said...

I just could not go away your web site before suggesting
that I actually loved the standard info an individual supply to your guests?

Is gonna be back incessantly in order to check up on
new posts

Take a look at my homepage ... More information

Anonymous said...

As the two most common and growing applications for solar water heater energy and has always been focused on
the UK government to guarantee that it will
be difficult at times. A major portion of that money goes to the oil industry -- and doesn't even support domestic production. Revenue solar water heater grew 26% year over year.

Here is my website: photovoltaic jordan

Anonymous said...

İstanbul Travel Guide

Traffic Exchange

Free Backlink

Website Stats

Pagerabk Check

Webmaster Tools

Rahman Mahmoodi said...
This comment has been removed by the author.