Skip to main content

C# Tutorial - The => (Lambda) Operator [Beginner]


C# 3 in .NET 3.5 got a number of handy new language features, but the one I'm enjoying the most at the moment is the addition of the => operator (otherwise know as lambda). While this operator does not add any new functionality to the language, it is a great piece of syntactic sugar.

So what does this syntactic sugar buy us? Well, in .NET 2.0, writing anonymous functions inline was a very verbose process. The code often looked ugly, and many times where anonymous methods would have served me perfectly well, I resorted to giving the function a name just to make the code look cleaner. No more! With the introduction of the => operator in .NET 3.5, anonymously inline functions now have a very clean look. It is not as clean as some other languages out there (scheme, for instance), but it is more than enough to make anonymous functions feel like they belong in your code, instead of looking like eyesores.

So enough of me yammering on about touchy-feely thing like 'clean code'. Lets see this operator in action. Below we have a Fold method in C# (actually the same exact code from a tutorial the other day on the paramskeyword). It takes a delegate that should take in 2 integers and return an integer value. That delegate will be 'folded' over the other parameters to the Fold function, and a single integer value will be returned.
public delegate int FoldIntDelegate(int a, int b);

public int Fold(FoldIntDelegate fid, params int[] list)
{
  int result = 1;
  foreach (int i in list)
    result = fid(result, i);
  return result;
}
 
So first, lets take a look at the verbose way of using this function. We explicitly create a FoldIntDelegate to pass into Fold, and then pass in a bunch of ints for Fold to work over.
int val = Fold(new FoldIntDelegate(delegate(int a, int b) { return a * b; }), 
               1, 3, 5, 7, 9);
 
That is pretty ugly, don't you think? Well, with .NET 2.0, we didn't quite have to write all that out. The FoldIntDelegate can be created implicitly:
int val = Fold(delegate(int a, int b) { return a * b; }, 1, 3, 5, 7, 9);
 
But that still is pretty verbose. Now look at all you have to write in .NET 3.5:
int val = Fold((a, b) => a * b, 1, 3, 5, 7, 9);
 
A very verbose 40 character inline method declaration gets trimmed by over half to a slim 15 character one. You no longer need to use the word delegate, you no longer need to declare the types of the parameters to the function (since they are already declared up where we said what a FoldIntDelegate actually was), and in certain cases we can get rid of curly-braces, parentheses, and the use of the 'return' keyword.

Here is another example:
List<int> list = new List<int>();

//The list gets populated with values

List<int> matches = list.FindAll(val => val != 9);
 
The FindAll function takes a Predicate<int> delegate, and with the lambda operator, it is real easy to create such a delegate. Since the Predicate<int> only takes one argument, we can even leave out the parentheses around the argument block.

Both examples we looked at so far only had one statement in the body of the anonymous function. This let us get away with not using curly braces or the return keyword. When there is more than one statement, we end up needing them again. For instance:
List<int> list = new List<int>();

//The list gets populated with values

List<int> matches = list.FindAll(val => {val = val * val; return val != 9; });
 
So once the body starts becoming more complex, it starts becoming verbose again. And yes, I know that could have been condensed down to a single statement - I just needed something to use as an example.

So there you go, the basic uses of the new lamdba operator in C# for .NET 3.5. I can already tell that it has the potential to change how I write C# code for certain situations, because of how much cleaner the end result feels - hopefully, all of you are enjoying this new operator as much as I am.

Comments

Popular posts from this blog

C# Snippet - Shuffling a Dictionary [Beginner]

Randomizing something can be a daunting task, especially with all the algorithms out there. However, sometimes you just need to shuffle things up, in a simple, yet effective manner. Today we are going to take a quick look at an easy and simple way to randomize a dictionary, which is most likely something that you may be using in a complex application. The tricky thing about ordering dictionaries is that...well they are not ordered to begin with. Typically they are a chaotic collection of key/value pairs. There is no first element or last element, just elements. This is why it is a little tricky to randomize them. Before we get started, we need to build a quick dictionary. For this tutorial, we will be doing an extremely simple string/int dictionary, but rest assured the steps we take can be used for any kind of dictionary you can come up with, no matter what object types you use. Dictionary < String , int > origin = new Dictionary < string , int >(); ...

C# WPF Printing Part 2 - Pagination [Intermediate]

About two weeks ago, we had a tutorial here at SOTC on the basics of printing in WPF . It covered the standard stuff, like popping the print dialog, and what you needed to do to print visuals (both created in XAML and on the fly). But really, that's barely scratching the surface - any decent printing system in pretty much any application needs to be able to do a lot more than that. So today, we are going to take one more baby step forward into the world of printing - we are going to take a look at pagination. The main class that we will need to do pagination is the DocumentPaginator . I mentioned this class very briefly in the previous tutorial, but only in the context of the printing methods on PrintDialog , PrintVisual (which we focused on last time) and PrintDocument (which we will be focusing on today). This PrintDocument function takes a DocumentPaginator to print - and this is why we need to create one. Unfortunately, making a DocumentPaginator is not as easy as...

C# WPF Tutorial - Implementing IScrollInfo [Advanced]

The ScrollViewer in WPF is pretty handy (and quite flexible) - especially when compared to what you had to work with in WinForms ( ScrollableControl ). 98% of the time, I can make the ScrollViewer do what I need it to for the given situation. Those other 2 percent, though, can get kind of hairy. Fortunately, WPF provides the IScrollInfo interface - which is what we will be talking about today. So what is IScrollInfo ? Well, it is a way to take over the logic behind scrolling, while still maintaining the look and feel of the standard ScrollViewer . Now, first off, why in the world would we want to do that? To answer that question, I'm going to take a an example from a tutorial that is over a year old now - Creating a Custom Panel Control . In that tutorial, we created our own custom WPF panel (that animated!). One of the issues with that panel though (and the WPF WrapPanel in general) is that you have to disable the horizontal scrollbar if you put the panel in a ScrollV...