Login | Register   
Twitter
RSS Feed
Download our iPhone app
TODAY'S HEADLINES  |   ARTICLE ARCHIVE  |   FORUMS  |   TIP BANK
Browse DevX
Sign up for e-mail newsletters from DevX


advertisement
 

From Delegate to Lambda

The key to understanding lambda expressions lies in understanding delegates.


advertisement
elegates play a tremendously important role in developing applications for the .NET Framework, especially when using C# or Visual Basic. Events, a special application of delegates, are used all over the framework. And the application and possibilities of delegates has only grown over time. C# 2.0 introduced the concept of anonymous methods and C# 3.0 and VB 9 take anonymous methods to the next level with lambda expressions. This article reviews the evolution of delegates and examines possibilities and syntax of delegates and lambdas in .NET 3.5.

Lambda expressions are the new hot thing in .NET 3.5. Almost a core element of applying LINQ, they offer a new syntax when implementing queries. I find a lot of people at user group meetings, code camps, and conferences struggling with the syntax of lambda expressions. At the core, the problem seems to be that developers have a hard time understanding what a lambda expression is. I tell them it's just a concise notation for a delegate. Blank faces look back. You have to really understand what a delegate is in order to understand that a lambda expression is little more than a delegate.

In this article I will look at some very basic code samples and take you from old school programming techniques to using lambda expressions in your code.

The World Without Delegates
Many programming languages don't use delegates. Guess what: People are still able to program valuable applications using these languages. This article looks at a basic program that takes a list of numbers, uses a method to apply a filter, selects only the even numbers, and then outputs these numbers to the console. Listing 1 and Listing 2 show what such a program might look like in C# and Visual Basic respectively.

The code in the application is functionally correct; it works and life is good. You can well imagine that instead of working with a generic list of integers you could use this same style of development to filter a list of customers or a table with orders.

However, in a lot of cases you'll find that just filtering one way is not enough. A different user might want the odd numbers or you may want to filter on customer location instead of customer name. If you proceed the way you started, you could end up having a GetOddNumbers method, a GetDivisibleByThree method, and many more custom methods. Not really efficient, right?—especially because you'll be re-implementing the same loop numerous times. It would be preferable to have just one select method with a parameter for the way you want to filter. But what should this parameter's type be?

What Is a Delegate?
Wikipedia defines a delegate as follows:

A delegate is a form of type-safe function pointer used by the .NET Framework. Delegates specify a method to call and optionally an object to call the method on. They are used, among other things, to implement callbacks and event listeners.

I personally like my own definition (of course, I'm a little biased):

A delegate definition is a signature description for a method.

A delegate defines a "template" for the return type, parameter types, and the order of a method's parameters.

It helps me to think of a delegate as an interface definition for methods. An interface defines a number of methods, properties, or events that need to be implemented by a class. You can use an interface definition as a type for a parameter in a method or a return type. Similarly you can use a delegate as a return type for a method or as the type for a parameter in a method.

You declare a delegate using the delegate keyword, for example:

// In C#: delegate void Print( string s ); ' in VB: Delegate Sub Print(ByVal s As String)

The snippet shows the declaration of a delegate, which has a return type void and takes a string as a parameter. You use the delegate name to indicate how or what the delegate should be applied to, but it is not part of the template. The following methods match the "template" set forth by the Print delegate:

// In C#: // matches delegate Print public void PrintToPaper( string text ){} // matches delegate Print private void PrintToConsole( string t ){} // matches delegate Print internal void DumpToLog( string s ){} ' in VB: ' matches delegate Print Public Sub PrintToPaper(ByVal text As String) End Sub ' matches delegate Print Private Sub PrintToConsole(ByVal t As String) End Sub ' matches delegate Print Friend Sub DumpToLog(ByVal s As String) End Sub

Note that all the above methods match with the delegate even though the names are not Print. They match because the return type is void and they have only one parameter of type string.

Equally the following methods are not a match with the Print delegate:



// In C#: // no match public void DumpToLog( string s, int logLevel ){} // no match internal string FormatToUpper( string s ) { return s.ToUpper(); } ' in VB: ' no match Sub DumpToLog(ByVal s As String, _ ByVal logLevel As Integer) End Sub ' no match Function FormatToUpper(ByVal s As String) _ As String Return s.ToUpper() End Function

The preceding functions are not a match because the DumpToLog method takes a different number of parameters and the FormatToUpper has a different return type.

Now that you know how to declare a delegate and you know when a method matches with the template defined by the delegate, how do you use the delegate? Back to the original problem: you want to filter a collection of data, in this case a collection of integers.

Editor's Note: This article was first published in the September/October 2008 issue of CoDe Magazine, and is reprinted here by permission.



Comment and Contribute

 

 

 

 

 


(Maximum characters: 1200). You have 1200 characters left.

 

 

Sitemap