1 / 17

Delegates and lambda functions Jim Warren, jim@cs.auckland.ac.nz

COMPSCI 280 S2 2014 Enterprise Software Development. Delegates and lambda functions Jim Warren, jim@cs.auckland.ac.nz. Today’s learning objectives. To understand and be able to apply C# language features in a variety of contexts for Development of delegates Use of lambda functions.

kat
Download Presentation

Delegates and lambda functions Jim Warren, jim@cs.auckland.ac.nz

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. COMPSCI 280 S2 2014Enterprise Software Development Delegates and lambda functions Jim Warren, jim@cs.auckland.ac.nz

  2. Today’s learning objectives • To understand and be able to apply C# language features in a variety of contexts for • Development of delegates • Use of lambda functions COMPSCI 280

  3. Delegates • Delegates are object-oriented, type-safe, and secure function pointers • A delegate is a reference type that defines a method signature • A delegate instance holds one or more methods • Methods can be static or non-static • Delegates allow methods to be passed as parameters. • Delegates can be used to define callback methods. • Delegates can be chained together; for example, multiple methods can be called on a single event. • It is a foundation of event handling. Job BOSS Finished??? Finished??? Call back when Finished COMPSCI280

  4. Creating Delegates • The type of a delegate is defined by the name of the delegate • Each delegate is limited to referencing methods of a particular kind only. The type is indicated by the delegate declaration – the input parameters and return type • Example: • Two methods with the same signature as the delegate declared above • Creating a New Delegate Object • Use the new operator • The argument is the method call, but without the arguments to the method • Delegate objects are immutable. (can’t change) • A delegate can reference static or instance method public delegate void Print(string s); public static void printToLower (string s) { Console.WriteLine("static: " + s.ToLower()); } public void printToUpper (string s) { Console.WriteLine("instance: " + s.ToUpper()); } Static method Print v1 = new Print(printToLower); Print v2 = new Print(new Program().printToUpper ); COMPSCI280

  5. Using Delegates • Once a delegate is instantiated, a method call made to the delegate will be passed by the delegate to that method and will call the underlying method • Use the name of the delegate, followed by the parenthesized arguments to be passed to the delegate output: static: this is a test Static method v1("This is a test"); v2("This is a test"); output: instance: THIS IS A TEST COMPSCI280

  6. Using Arrays • Create an array of delegate objects • Instantiate each delegate object with various instance methods defined above • Note: In C#, if we reference a method on an object (omitting the parentheses), C# instead treats the method name like a field, returning the object representing that method. • Call each delegate object by using a loop -> invoke the underlying method public delegate void Print(string s); Print[] arr = new Print[2]; arr[0] = new Print(printToLower); arr[1] = new Print(new Program().printToUpper); foreach (Print p in arr) p("In an array"); static: in an array instance: IN AN ARRAY COMPSCI280

  7. Named & Anonymous methods public delegate void Print(string s); • Named Method • A delegate can be associated with a named method. • When you instantiate a delegate using a named method, the method is passed as a parameter • The method that you pass as a delegate parameter must have the same signature as the delegate declaration. • A delegate instance may encapsulate either a static or an instance method. • Anonymous Method • In C# 2.0 (from 2005), you can declare a delegate using an anonymous method Named method Print v1 = printToLower; v1("This is another test"); Print v2 = new Program().printToUpper; v2("This is another test"); Print a1 = delegate(string j){ Console.WriteLine("Anonymous:" + j); }; a1("Well done"); Anonymous method COMPSCI280

  8. Multicast delegates • Delegate objects can be assigned to one delegate instance to be multicast using the + operator. • A delegate can simultaneously reference multiple methods, and it will invoke all underlying methods • Methods are invoked sequentially, in the order added. • Conditions: • Only delegates of the same type can be composed. • The - operator can be used to remove a component delegate from a composed delegate. public delegate void Print(string s); A delegate object Print mp2 = null; mp2 += printToLower; mp2 += new Program().printToUpper; mp2("Hello World"); Output: static: hello world Instance: HELLO WORLD COMPSCI280

  9. Delegate Sender Receiver Event • Event Basic: • An event is a message sent by an object to signal the occurrence of an action. • The action could be caused by user interaction, such as a mouse click, or it could be triggered by some other program logic. • The object that raises the event is called the event sender. • The object that captures the event and responds to it is called the event receiver. • The event sender class doesn’t know which object or method will receive (handle) the events it raises. What is needed is an intermediary (or pointer-like mechanism, delegate) between the source and the receiver. • An event is a member of a delegate type that enables an object or class to provide notifications. COMPSCI280

  10. Example: • Declare a delegate that takes two parameters: • the source that raised the event, and • the data for the event • In the Button class (e.g. in a Windows Forms Application) • Defines a click event of type EventHandler • Inside the Button class, the click member is exactly like a field of type EventHandler • Outside the Button class, the click member can only be used on the left-hand side of the += and -= operators. • The += operator adds a handler for the event and -= removes a handler for the event public delegate void EventHandler(object sender, System.EventArgs e); public class Button { public event EventHandler Click; public void Reset() { Click = null; } … COMPSCI280

  11. A lot of this is set up for you when your create a new Windows Forms Application in VS and drag a button onto it. Example: • In the Form1 class (Windows application) • Create a button object • Create a event handler method • Connect the event handler method to the click event of the button object • You can also reuse the same method for multiple events public Form1() { ... button1.Click += new EventHandler(button1_Click); } public void button1_Click(object sender, EventArgs e){ Console.WriteLine("Clicked"); } Event handler method button2.Click += new EventHandler(button1_Click); button3.Click += new EventHandler(button1_Click); COMPSCI280

  12. Lambda expressions Borrowing liberally from http://msdn.microsoft.com/en-us/library/bb397687.aspx • A lambda expression is • An anonymous function used to create delegates or expression tree* types • Denoted with => • Can pronounce as ‘maps to’, ‘such that’ or ‘for which’ • Same order of operations precedence as assignment with = • Lambda expressions let you write local functions that can be passed as arguments or returned as the value of function calls • Particularly helpful for writing LINQ query expressions • You can assign a lambda expression to a delegate type * See next slide COMPSCI 280

  13. Expression trees • Holding an expression in a dynamic structure • For C# this is as a nested series of objects • E.g. a binary operator like + can have Left andRight terms, each of which themselves mightbe variables, constants or other operators • A lambda expression is just ‘syntacticsugar’ • It’s an easier way to write stuff that thecompiler turns into delegate definitionsor expression trees • Great further explanation at https://www.youtube.com/watch?v=P60pt5xlms0 and https://www.youtube.com/watch?v=0YJECE45jhk • Author Jamie King almost sounds drunk, but I think that’s just his natural speaking style (a+b)*c+7http://commons.wikimedia.org/wiki/File:Exp-tree-ex-11.svg COMPSCI 280

  14. Syntactic sugar • So as Jamie King illustrates on YouTube Func<int, bool> test= i => i > 5; • Is equivalent to static bool qwerty(inti) { return i > 5; } and thenFunc<int,bool> test=qwerty; • Either way, you can do • Console.Writeline(test(3));Console.Writeline(test(8)); False True COMPSCI 280

  15. Definition • Expression lambda • In general looks like (x, y) => x==y • When there’s only one parameter you can skip the parentheses • Statement lambda • Statements in curly braces for the right-hand side of the lambda • The above example is a function of type void, but you could include one or more return statements in the code, too • E.g. to perform a logical test for a bool delegate or compute a number for an int delegate COMPSCI 280

  16. Use in queries • Very convenient in interaction with LINQ • The type of the first input (e.g. the ‘n’ above) is inferred to be the type of the elements in the source sequence • So if we are using a database connection we may have the result of referencing a table or from a query, such asIEnumerable<Customer> (iterator on a set of Customer instances) • And then we can do a query like:customers.Where(c => c.City == "London"); • In this case the ‘c’ has access to the Customer object’s properties (e.g. the City property, which might’ve been sourced from a field of that name in a customer table under MySQL) Using an array as the data source for the query in this case Read “Customers, c, such that c’s city is London” COMPSCI 280

  17. Where we’re up to • That’s it for lectures from me (Jim) this semester • Note for your exam preparation that this section of the course has changed a LOT since last year (or earlier years) • Previously you’d see an extensive section of C# as an alternative programming language to Java without putting it to work in neat ways like MVC • Also we had taught a lot of Windows Forms stuff that looks too much like the GUI programming in 230 (and besides, Web based interfaces are much more ‘Enterprise’) • Now you’re over to Radu for 3 weeks and then a wrap-up from Ulrich • Feel free to contact me with exam questions • On leave week of Oct 20, but otherwise should be responsive on jim@cs.auckland.ac.nz COMPSCI 280

More Related