420 likes | 548 Views
Getting the Most from Lambda Expressions. Deborah Kurata President InStep Technologies, Inc Session Code: DTL315. Deborah Kurata is. Consultant and President of: InStep Technologies, Inc. Author of: Doing Objects in VB 2005 Best Kept Secrets in .NET Software designer/developer
E N D
Getting the Most from Lambda Expressions Deborah Kurata President InStep Technologies, Inc Session Code: DTL315
Deborah Kurata is... • Consultant and President of:InStep Technologies, Inc. • Author of: • Doing Objects in VB 2005 • Best Kept Secrets in .NET • Software designer/developer • INETA Speaker • Microsoft MVP • DeborahK@insteptech.com
InStep Technologies is... • Consulting • Mentoring services to get you started and keep you going with .NET • Strategic software consulting and training services • Application architecture and design • Custom software development of Windows and Web-based applications • Web site: www.insteptech.com
You Are... • Using Generic Lists • List(Of Customer) • List<Customer> • Using Lambda Expressions • Just getting started/new to them • Use them once in a while • Use them everyday
This Presentation is … • Fun with Lambda Expressions • What are Lambda Expressions? • Lambdas as Generic Delegates • Lambdas as Callable Entities • Lambdas as Callbacks
Generic Lists • Class Customer • Manages a single customer • Customer properties • Customer methods • Class Customers • Manages the list of customers • List(Of Customer) • List<Customer>
demo Fun With Lambda Expressions
Lambda Calculus • “Formal system designed to investigate function definition, function application, and recursion.” • Wikipedia
What are Lambda Expressions? • New in Visual Basic 9 and C# 3.0 (VS 2008) • Unnamed, inline functions • Single statement • Multiple statement (C# only; coming in VB 10) • Used wherever delegates are required
What is a Delegate? • An object that holds a reference to a method with a particular parameter list and return type • Like object-oriented, type-safe function pointer • Make it possible to treat methods as entities • Assign to variables • Pass as parameters
Classic Delegate Example: Events // Passes the method to the new delegate HelloButton.Click += new EventHandler(HelloButton_Click); ' AddressOf assigns the address of the ' method to the delegate AddHandler HelloButton.Click, _ AddressOf HelloButton_Click
Using Lambda Expressions // C# HelloButton.Click += (s, ev) => MessageBox.Show("Hello World"); ' VB: AddHandler HelloButton.Click, _ Function(s, ev) _ MessageBox.Show("Hello World")
Defining Delegates • Named method • Anonymous method (C# 2.0) • Lambda expression (C# 3.0 and VB 9)
Lambda Expression Syntax - VB ' General syntax: Dim foundCustomer as Customer = _ allCust.First(Function(c as Customer) _ c.CustomerId = 4) ' With inferred typing: Dim foundCustomer = _ allCust.First(Function(c) _ c.CustomerId = 4)
Lambda Expression Syntax – C# ' General syntax: Customer foundCustomer = allCust.First((Customer c) => c.CustomerId == 4); ' With inferred typing: varfoundCustomer = allCust.First(c => c.CustomerId == 4);
Lambda Multiline Syntax – C# var foundCustomer = allCust.First(c => { Debug.WriteLine(c.FullName); if (c.CustomerId == 4) return true; else return false; });
Features that Use Delegates • Event handlers • Enumerable class methods • Extension methods of IEnumerable(T) • Examples: Aggregate, All, Any, FirstOrDefault • LINQ methods • Used by LINQ • Examples: OrderBy, Where, GroupBy
Lambdas as Generic Delegates • Generic delegates were new in .NET 2.0 • Predicate Delegates • Action Delegates • Func Delegates
Predicate Delegate • Predicate: “An operator or function which returns a Boolean value” - Wikipedia • Encapsulates a method that evaluates to True or False • Takes one parameter
Example: Predicate Delegate ' VB: Dim foundCustomer = _ Array.Find(custArray, Function(c) _ c.LastName.StartsWith("K")) // C#: varfoundCustomer = Array.Find(custArray, c => c.LastName.StartsWith("K"));
demo Predicate Delegates
Action Delegate • Encapsulates a method that does not return a value • Sub in VB • void in C# • Takes up to four parameters
Example: Action Delegate ' VB: Can only use named methods allCust.ForEach(AddressOfWriteToDebug) // C#: allCust.ForEach(c => Debug.WriteLine(c.FullName));
demo Action Delegates
Func Delegate • Encapsulates a method that returns a value • Takes up to 4 parameters and a return value • Last parameter is the return value • Func<int, int, string> • Func(Of Integer, Integer, String)
Example: Func Delegate ' VB: Dim total = allCust.Sum(Function(c) _ c.SalesTotal) // C#: var total = allCust.Sum(c => c.SalesTotal);
demo Func Delegates
Lambdas as Callable Entities • Lambda expressions can be assigned to a delegate variable • Lambda expression is executed when the delegate is executed
Example: Assignment ' VB: Infers the type Dim f = _ Function(x as Integer) (x + x).ToString() Debug.WriteLine(f(5)) Debug.WriteLine(f(10)) // C#: Func<int,string> f = x => (x + x).ToString(); Debug.WriteLine(f(5)); Debug.WriteLine(f(10));
Lambda Expression Execution • Lambda expressions are executed when they are called, not when they are constructed • Local variables used in a lambda expression are “captured” or “lifted” • Variable value used is the value at execution time • Variable lifetime extends to the lifetime of the delegate
Example: Local Variables // C#: int y = 0; Func<int,string> f = x => (x + y).ToString(); y = 10; Debug.WriteLine(f(5)); ' VB: Dim y As Integer = 0 Dim f As Func(Of Integer, String) = _ Function(x) (x + y).ToString() y = 10 Debug.WriteLine(f(5))
demo Callable Entities
Lambdas as Callbacks • Callback • “Executable code that is passed as an argument to other code” • Passes a function to a function • A delegate does not know or care about the class of the method it is referencing • No need to reference the class that defined the method
demo Callbacks
Getting the Most from Lambdas • Use Lambda expressions for • Writing inline functions • Calling LINQ methods • Calling extension methods that take a delegate • Creating callable functions • Performing callbacks
Resources • www.microsoft.com/teched Sessions On-Demand & Community • www.microsoft.com/learning • Microsoft Certification & Training Resources • http://microsoft.com/technet • Resources for IT Professionals • http://microsoft.com/msdn Resources for Developers www.microsoft.com/learning Microsoft Certification and Training Resources
Related Content DTL336 Future Directions for Visual Basic Presenter(s): Jonathan Aneja, Anders Hejlsberg DTL402 How LINQ Works: A Deep Dive into the Microsoft Visual Basic and C# Implementations Presenter: Jonathan Aneja
Track Resources Visit the DPR TLC for a chance to win a copy of Visual Studio Team Suite. Daily drawing occurs every day in the TLC at 4:15pm. Stop by for a raffle ticket http://www.microsoft.com/visualstudio http://www.microsoft.com/visualstudio/en-us/products/teamsystem/default.mspx Please visit us in the TLC blue area
© 2009 Microsoft Corporation. All rights reserved. Microsoft, Windows, Windows Vista and other product names are or may be registered trademarks and/or trademarks in the U.S. and/or other countries. The information herein is for informational purposes only and represents the current view of Microsoft Corporation as of the date of this presentation. Because Microsoft must respond to changing market conditions, it should not be interpreted to be a commitment on the part of Microsoft, and Microsoft cannot guarantee the accuracy of any information provided after the date of this presentation. MICROSOFT MAKES NO WARRANTIES, EXPRESS, IMPLIED OR STATUTORY, AS TO THE INFORMATION IN THIS PRESENTATION.