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

Slides:



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

Delegates and lambda functions Jim Warren, COMPSCI 280 S Enterprise Software Development.
The Web Warrior Guide to Web Design Technologies
Copyright W. Howden1 Lecture 7: Functional and OO Design Descriptions.
1 Programming for Engineers in Python Autumn Lecture 5: Object Oriented Programming.
Programming Based on Events
About the Presentations The presentations cover the objectives found in the opening of each chapter. All chapter objectives are listed in the beginning.
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.
Extension Methods Programming in C# Extension Methods CSE Prof. Roger Crawfis.
Eric Vogel Software Developer A.J. Boggs & Company.
Introduction to Graphical User Interfaces. Objectives * Students should understand what a procedural program is. * Students should understand what an.
Tutorial 11 Using and Writing Visual Basic for Applications Code
Introduction to Object Oriented Programming. Object Oriented Programming Technique used to develop programs revolving around the real world entities In.
1 Web-Enabled Decision Support Systems Objects and Procedures Don McLaughlin IE 423 Design of Decision Support Systems (304)
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.
ASP.NET Programming with C# and SQL Server First Edition Chapter 3 Using Functions, Methods, and Control Structures.
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.
Session 08 Module 14: Generics and Iterator Module 15: Anonymous & partial class & Nullable type.
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
An Object-Oriented Approach to Programming Logic and Design Fourth Edition Chapter 6 Using Methods.
CPS120: Introduction to Computer Science Decision Making in Programs.
CPS120: Introduction to Computer Science Lecture 14 Functions.
Data TypestMyn1 Data Types The type of a variable is not set by the programmer; rather, it is decided at runtime by PHP depending on the context in which.
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)
C++ How to Program, 9/e © by Pearson Education, Inc. All Rights Reserved.
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.
Callback Functionality and Event-Driven Programming
Java Programming: From Problem Analysis to Program Design, 3e Chapter 6 Graphical User Interface (GUI) and Object-Oriented Design (OOD)
Chapter 5 Introduction to Defining Classes
 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.
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.
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.
Overview of Previous Lesson(s) Over View  ASP is a technology that enables scripts in web pages to be executed by an Internet server.  ASP.NET is a.
CGS 3066: Web Programming and Design Spring 2016 Programming in JavaScript.
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.
C# Fundamentals An Introduction. Before we begin How to get started writing C# – Quick tour of the dev. Environment – The current C# version is 5.0 –
Chapter 5 Introduction to Defining Classes Fundamentals of Java.
Programming Paradigms, Software Architectural Patterns, and MVC CS 378 – Mobile Computing for iOS Dr. William C. Bulko.
Chapter 9 Programming Based on Events
Chapter 15 Event-Driven Programming and Animations
INF230 Basics in C# Programming
Delegates and Events Svetlin Nakov Telerik Corporation
UNIT - V STORED PROCEDURE.
Chapter Eleven Handling Events.
.NET and .NET Core 5.2 Type Operations Pan Wuming 2016.
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
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 COMPSCI2803  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 COMPSCI2804  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 COMPSCI2805  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 COMPSCI2806  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 COMPSCI2807  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 COMPSCI2808  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 COMPSCI2809  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: COMPSCI28010  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: COMPSCI28011  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 COMPSCI Borrowing liberally from us/library/bb aspx

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

Conclusion  The ability to have variables reference functions is powerful  Allows us to achieve a high degree of modularity between a ‘supervisor’ procedure and the procedures delegated to do subtasks  Provides a powerful framework for event handling  Useful for many things, including responding to user actions in a Graphical User Interface (GUI)  Lambda expressions are a convenient syntax for plugging anonymous functions into your code  Useful for many things including implementing query criteria  Keep (or get!) going with assignment 2  Next – we’ll look at further useful VS and C# features COMPSCI 28017