Content by Category
.NET 1.x
.NET 2.0
.NET 3.0
.NET 3.5
.NET 4.0
.NET Assemblies
.NET Framework
.NET Getting Started
Accessibility
ADO.NET
Advertorials
Agile Development
AJAX
Architecture
ASP.NET
ASP.NET MVC
ASP.NET WebForms
Azure
B2B (Business Integration)
Bing
BizTalk
Book Excerpts
Build and Deploy
C#
C++
ClickOnce
Cloud Computing
Code Contracts
CODE on the Road!
COM+
Community
Conferences
Continuous Integration
Crystal Reports
CSLA.NET
CSS
Data
Design Patterns
Development Process
Display Technologies
Distributed Computing
DotNetNuke
DSL
Dynamic Programming
Editorials
Enterprise Services ("COM+")
Entity Framework
Events
Expression Blend
F#
Fox to Fox
Frameworks
Functional Programming
Git
Graphics
Internet Explorer 8.0
Interviews
iPhone
Iron Ruby
Java
Java Script
jQuery
LINQ
Linux
Mac OS X
MDX
Microsoft Application Blocks
Microsoft Business Rules Framework
Microsoft Dynamics
Microsoft Expression
Microsoft Office
Mobile Development
Mobile PC
Mono
MsBuild
Network
NHibernate
Object Oriented Development
Open Source
Opinion
Opinions
Oracle
ORM
Other Languages
Parallel Programming
Patterns
Podcasts
Post Mortem
PowerPoint
Print/Output
Product News
Product Reviews
Project Management
Python
Q&A
Rails
Rake
Reporting Services
REST
RIA Services
Ruby
Ruby on Rails
Search
Security
Services
SharePoint
Silverlight
SOA
Social Networks
Software & Law
Software Business
Source Control
Speech-Enabled Applications
SQL Server
SQL Server 2000
SQL Server 2005
SQL Server 2008
SQL Server CE/AnyWhere/Mobile/Compact
Subversion
Sync Framework
Tablet PC
TDD
Team System
Techniques
Testing and Quality Control
Tips
UI Design
UML
User Groups
VB Script
VB.NET
Version Control
VFP and .NET
VFP and SQL Server
Virtual Earth
Vista
Visual Basic
Visual Basic 6 (and older)
Visual FoxPro
Visual Studio .NET
Visual Studio 2005
Visual Studio 2008
Visual Studio 2010
Visual Studio Tools for Office
VSX
WCF
Web Development (general)
Web Services
WF
Whitepapers
Windows 7
Windows Azure
Windows Live
Windows Server
Windows Vista
WinForms
Workflow
WPF
XAML
XML
XNA
XSLT



DevConnections


 


CODE TRAINING

Reader rating:
Click here to read 1 comment about this article.
Article source: CoDe (2008 Sep/Oct)


Article Pages:  1  2 - Next >


From Delegate to Lambda

The key to understanding lambda expressions is understanding delegates. Delegates 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 since 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:

C#:

delegate void Print( string s );

VB:

Delegate Sub Print(ByVal 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 name of the delegate to indicate what the application of the delegate will be, but it is not part of the template. The following methods match the “template” set forth by the Print delegate:

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 ){}

VB:

' matches delegate Print
Public Sub PrintToPaper(ByVal text As String)
End Sub
' matches delegate Print
Private Sub PrintToConsole(ByVal As String)
End Sub

' matches delegate Print
Friend Sub DumpToLog(ByVal 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:

C#:

// no match
public void DumpToLog( string s, int logLevel ){}

// no match
internal string FormatToUpper( string s )
{
    return s.ToUpper();
}

VB:

' no match
Sub DumpToLog(ByVal As String, _
              ByVal logLevel As Integer)
End Sub

' no match
Function FormatToUpper(ByVal As String
                       As String
    Return s.ToUpper()
End Function

The above 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.

&

By: Mark Blomsma

Mark Blomsma is a software developer, software architect, author, and speaker specializing in Microsoft .NET technologies. He’s been working as an IT professional for more than 14 years and is currently an independent contractor through his company Develop-One (www.develop-one.com). He is a freelance instructor for DevelopMentor and has received the Microsoft MVP for his community contributions five years running.

mark.blomsma@develop-one.com

Fast Facts

In Visual Baisc, the RemoveHandler statement is an exception to the lambda = delegate rule. You cannot pass in a lambda expression for the delegate parameter of RemoveHandler.



Article Pages:  1  2 - Next Page: 'Filtering with Delegates' >>

Page 1: From Delegate to Lambda
Page 2: Filtering with Delegates

How would you rate the quality of this article?
1 2 3 4 5
Poor      Outstanding

Tell us why you rated the content this way. (optional)

Average rating:
3.8 out of 5

11 people have rated this article.

      Hacker Halted

 

DevLink