Delegates and lambda functions Jim Warren, COMPSCI 280 S2 2014 Enterprise Software Development.

Slides:



Advertisements
Similar presentations
Copyright © 2012 Pearson Education, Inc. Chapter 9 Delegates and Events.
Advertisements

The Web Warrior Guide to Web Design Technologies
George Blank University Lecturer. CS 602 Java and the Web Object Oriented Software Development Using Java Chapter 4.
COMP171 Data Structure & Algorithm Tutorial 1 TA: M.Y.Chan.
Programming Based on Events
11/1/06 1 Hofstra University, CSC005 Chapter 8 (Part 3) High Level Programming Languages.
About the Presentations The presentations cover the objectives found in the opening of each chapter. All chapter objectives are listed in the beginning.
Object-Oriented Analysis and Design
2.3 Cool features in C# academy.zariba.com 1. Lecture Content 1.Extension Methods 2.Anonymous Types 3.Delegates 4.Action and Func 5.Events 6.Lambda Expressions.
Cs164 Prof. Bodik, Fall Symbol Tables and Static Checks Lecture 14.
Graphical User Interfaces A Quick Outlook. Interface Many methods to create and “interface” with the user 2 most common interface methods: – Console –
Programming Handheld and Mobile devices 1 Programming of Handheld and Mobile Devices Lecture 20 Microsoft’s Approach 3 – C# Rob Pooley
Programming Paradigms Imperative programming Functional programming Logic programming Event-driven programming Object-oriented programming A programming.
C# Event Processing Model Solving The Mystery. Agenda Introduction C# Event Processing Macro View Required Components Role of Each Component How To Create.
CS2110 Recitation 07. Interfaces Iterator and Iterable. Nested, Inner, and static classes We work often with a class C (say) that implements a bag: unordered.
Extension Methods Programming in C# Extension Methods CSE Prof. Roger Crawfis.
Tutorial 11 Using and Writing Visual Basic for Applications Code
Delegates and lambda functions Jim Warren, COMPSCI 280 S Enterprise Software Development.
BIM211 – Visual Programming Objects, Collections, and Events 1.
Putting it all together: LINQ as an Example. The Problem: SQL in Code Programs often connect to database servers. Database servers only “speak” SQL. Programs.
CSE115: Introduction to Computer Science I Dr. Carl Alphonce 343 Davis Hall
20-753: Fundamentals of Web Programming 1 Lecture 12: Javascript I Fundamentals of Web Programming Lecture 12: Introduction to Javascript.
Sample Application Multi Layered Architecture (n-tier): –Graphical User Interface (GUI): Forms, components, controls The Visual Designer in Visual Studio.
1 Chapter Eleven Handling Events. 2 Objectives Learn about delegates How to create composed delegates How to handle events How to use the built-in EventHandler.
Delegates and Events Callback Functionality and Event-Driven Programming Svetlin Nakov Technical Trainer Software University
CPS120: Introduction to Computer Science Decision Making in Programs.
Built-in Data Structures in Python An Introduction.
CPS120: Introduction to Computer Science Lecture 14 Functions.
Introduction to C#. Why C#? Develop on the Following Platforms ASP.NET Native Windows Windows 8 / 8.1 Windows Phone WPF Android (Xamarin) iOS (Xamarin)
Programming in Java CSCI-2220 Object Oriented Programming.
Object-Oriented Program Development Using Java: A Class-Centered Approach, Enhanced Edition.
CS-1020 Dr. Mark L. Hornick 1 Event-Driven Programming.
Chapter 2: Variables, Functions, Objects, and Events JavaScript - Introductory.
PROGRAMMING IN VISUAL BASIC.NET VISUAL BASIC PROGRAMMING FUNDAMENTALS Bilal Munir Mughal 1 Chapter-8.
Module 8: Delegates and Events. Overview Delegates Multicast Delegates Events When to Use Delegates, Events, and Interfaces.
JavaScript, Fourth Edition
Callback Functionality and Event-Driven Programming
 Objects versus Class  Three main concepts of OOP ◦ Encapsulation ◦ Inheritance ◦ Polymorphism  Method ◦ Parameterized ◦ Value-Returning.
CHARLES UNIVERSITY IN PRAGUE faculty of mathematics and physics Advanced.NET Programming I 10 th Lecture Pavel Ježek
Inside LINQ to Objects How LINQ to Objects work Inside LINQ1.
Introduction to Object-Oriented Programming Lesson 2.
From C++ to C# Part 5. Enums Similar to C++ Similar to C++ Read up section 1.10 of Spec. Read up section 1.10 of Spec.
CMSC 202 Advanced Section Classes and Objects: Object Creation and Constructors.
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All rights reserved. 1 Chapter 15 Event-Driven Programming and.
Architecture Multi Layered Architecture (n-tier): Application: Model Controllers Database Access Graphical User Interface (GUI): Forms, components, controls.
More about Java Classes Writing your own Java Classes More about constructors and creating objects.
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All rights reserved. 1 Chapter 15 Event-Driven Programming and.
IAP C# 2011 Lecture 2: Delegates, Lambdas, LINQ Geza Kovacs.
A High Flying Overview CS139 – Fall 2006 How far we have come.
CGS 3066: Web Programming and Design Spring 2016 Programming in JavaScript.
User Interface Programming in C#: Basics and Events Chris North CS 3724: HCI.
M1G Introduction to Programming 2 2. Creating Classes: Game and Player.
Arrays & Enum & Events. Arrays Arrays are data structures consisting of related data items of the same type. Arrays are fixed-length entities—they remain.
 ASP.NET provides an event based programming model that simplifies web programming  All GUI applications are incomplete without enabling actions  These.
OPERATORS IN C CHAPTER 3. Expressions can be built up from literals, variables and operators. The operators define how the variables and literals in the.
Functional Programming Data Aggregation and Nested Queries Ivan Yonkov Technical Trainer Software University
Chapter 9 Programming Based on Events
INF230 Basics in C# Programming
Advanced .NET Programming I 4th Lecture
Chapter Eleven Handling Events.
Programming Language Concepts (CIS 635)
C# Event Processing Model
6 Delegate and Lambda Expressions
Lecture 15 (Notes by P. N. Hilfinger and R. Bodik)
Delegates & Events 1.
Object Oriented Practices
„Lambda expressions, Optional”
Advanced .NET Programming I 4th Lecture
Chengyu Sun California State University, Los Angeles
Events, Delegates, and Lambdas
Presentation transcript:

Delegates and lambda functions Jim Warren, COMPSCI 280 S Enterprise Software Development

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 2802

Delegates Handout7COMPSCI2803  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. BOSS Job Finished??? Call back when Finished

Creating Delegates Handout7COMPSCI2804  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()); } Print v1 = new Print(printToLower); Print v2 = new Print(new Program().printToUpper ); Static method

Using Delegates Handout7COMPSCI2805  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 v1("This is a test"); v2("This is a test"); Static method output: static: this is a test output: instance: THIS IS A TEST

Using Arrays Handout7COMPSCI2806  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 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"); public delegate void Print(string s); static: in an array instance: IN AN ARRAY

Named & Anonymous methods Handout7COMPSCI2807  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 public delegate void Print(string s); Print v1 = printToLower; v1("This is another test"); Print v2 = new Program().printToUpper; v2("This is another test"); Named method Print a1 = delegate(string j){ Console.WriteLine("Anonymous:" + j); }; a1("Well done"); Anonymous method

Multicast delegates Handout7COMPSCI2808  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); Print mp2 = null; mp2 += printToLower; mp2 += new Program().printToUpper; mp2("Hello World"); Output: static: hello world Instance: HELLO WORLD A delegate object

Event Handout7COMPSCI2809  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. SenderReceiver Delegate

Example: Handout7COMPSCI28010  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; } …

Example: Handout7COMPSCI28011  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); 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.

Lambda expressions  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 Handout 07COMPSCI Borrowing liberally from us/library/bb aspx

Expression trees Handout 07COMPSCI (a+b)*c+7 tree-ex-11.svg  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 and Right terms, each of which themselves might be variables, constants or other operators  A lambda expression is just ‘syntactic sugar’  It’s an easier way to write stuff that the compiler turns into delegate definitions or expression trees  Great further explanation at and  Author Jamie King almost sounds drunk, but I think that’s just his natural speaking style

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

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 Handout 07COMPSCI 28015

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 as IEnumerable (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) Handout 07COMPSCI Using an array as the data source for the query in this case Read “Customers, c, such that c’s city is London”

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 Handout 07COMPSCI 28017