Delegates and Events Tom Roeder CS215 2006fa. Motivation – Function Pointers Treat functions as first-class objects eg. Scheme: (map myfunc somelist)

Slides:



Advertisements
Similar presentations
pa 1 Porting BETA to ROTOR ROTOR Projects Presentation Day, June by Peter Andersen.
Advertisements

Copyright © 2012 Pearson Education, Inc. Chapter 9 Delegates and Events.
CS  C++ Function Pointers  C# Method References  Groundwork for Lambda Functions.
C# Types Tom Roeder CS fa. Administration CMS is up let me know if you can’t see the course Assignments are posted may not be able to do some.
CSE341: Programming Languages Lecture 11 Closures-ish Java & C Dan Grossman Fall 2011.
George Blank University Lecturer. CS 602 Java and the Web Object Oriented Software Development Using Java Chapter 4.
Programming with Java © 2002 The McGraw-Hill Companies, Inc. All rights reserved. 1 Chapter 12 More OOP, Interfaces, and Inner Classes.
Road Map Introduction to object oriented programming. Classes
Button click handlers Maarten Pennings. Introduction An activity has one or more views – view is also known as widget or control – examples include Button,
C#.NET C# language. C# A modern, general-purpose object-oriented language Part of the.NET family of languages ECMA standard Based on C and C++
Interfaces. In this class, we will cover: What an interface is Why you would use an interface Creating an interface Using an interface Cloning an object.
Evan Korth New York University Computer Science I Classes and Objects Professor: Evan Korth New York University.
The Composite Pattern.. Composite Pattern Intent –Compose objects into tree structures to represent part-whole hierarchies. –Composite lets clients treat.
Lecture 9 Concepts of Programming Languages
Templates. Objectives At the conclusion of this lesson, students should be able to Explain how function templates are used Correctly create a function.
Abstract Data Types and Encapsulation Concepts
Generic Subroutines and Exceptions CS351 – Programming Paradigms.
8.1 Classes & Inheritance Inheritance Objects are created to model ‘things’ Sometimes, ‘things’ may be different, but still have many attributes.
PARALLEL PROGRAMMING ABSTRACTIONS 6/16/2010 Parallel Programming Abstractions 1.
Week 4-5 Java Programming. Loops What is a loop? Loop is code that repeats itself a certain number of times There are two types of loops: For loop Used.
Singleton Christopher Chiaverini Software Design & Documentation September 18, 2003.
Extension Methods Programming in C# Extension Methods CSE Prof. Roger Crawfis.
Introduction to Java Prepared by: Ahmed Hefny. Outline Classes Access Levels Member Initialization Inheritance and Polymorphism Interfaces Inner Classes.
Hoang Anh Viet Hà Nội University of Technology Chapter 1. Introduction to C# Programming.
Programming using C# for Teachers Introduction to Objects Reference Types Functions of Classes Attributes and Types to a class LECTURE 2.
1 SystemVerilog Enhancement Requests Daniel Schostak Principal Engineer February 26 th 2010.
C# EMILEE KING. HISTORY OF C# In the late 1990’s Microsoft recognized the need to be able to develop applications that can run on multiple operating system.
Chapter 15 Introduction to PL/SQL. Chapter Objectives  Explain the benefits of using PL/SQL blocks versus several SQL statements  Identify the sections.
1 Interfaces and Abstract Classes Chapter Objectives You will be able to: Write Interface definitions and class definitions that implement them.
[ISRAR ALI] Hammad Khan. The namespace keyword is used to declare a scope. Making software components reusable can result in naming collisions (two classes.
Chapter 14 Abstract Classes and Interfaces. Abstract Classes An abstract class extracts common features and functionality of a family of objects An abstract.
Advanced C# Types Tom Roeder CS fa. From last time out parameters difference is that the callee is required to assign it before returning not the.
Programming With Java ICS201 University Of Ha’il1 Chapter 7 Inheritance.
UMass Lowell Computer Science Java and Distributed Computing Prof. Karen Daniels Fall, 2000 Lecture 9 Java Fundamentals Objects/ClassesMethods Mon.
Design Patterns Software Engineering CS 561. Last Time Introduced design patterns Abstraction-Occurrence General Hierarchy Player-Role.
CHARLES UNIVERSITY IN PRAGUE faculty of mathematics and physics Advanced.NET Programming I 10 th Lecture Pavel Ježek
Chapter 7: Class Inheritance F Superclasses and Subclasses F Keywords: super and this F Overriding methods F The Object Class F Modifiers: protected, final.
FEN 2014UCN Teknologi/act2learn1 Higher order functions Observer Pattern Delegates Events Visitor Pattern Lambdas and closures Lambdas in libraries.
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.
1 CS Programming Languages Class 22 November 14, 2000.
1 Copyright © 1998 by Addison Wesley Longman, Inc. Chapter 10 Abstraction - The concept of abstraction is fundamental in programming - Nearly all programming.
Programming in java Packages Access Protection Importing packages Java program structure Interfaces Why interface Defining interface Accessing impln thru.
Singleton Pattern. Problem Want to ensure a single instance of a class, shared by all uses throughout a program Context Need to address initialization.
CH10 Supplementary Material Prepared by Fatimah Alakeel Oct 2010.
V 1.0 OE-NIK HP 1 Advanced Programming Delegates, Events.
Object Oriented Programming in Java Habib Rostami Lecture 10.
Reference Types CSE301 University of Sunderland Harry R Erwin, PhD.
(c) University of Washington05-1 CSC 143 Java Abstract Classes and Frameworks Reading: Ch. 11.
Array and Pointers An Introduction Unit Unit Introduction This unit covers the usage of pointers and arrays in C++
UMass Lowell Computer Science Java and Distributed Computing Prof. Karen Daniels Fall, 2000 Lecture 10 Java Fundamentals Objects/ClassesMethods.
Mr H Kandjimi 2016/01/03Mr Kandjimi1 Week 3 –Modularity in C++
Object Based Programming Chapter 8. 2 Contrast ____________________ Languages –Action oriented –Concentrate on writing ________________ –Data supports.
C# for C++ Programmers 1.
Generics, Lambdas, Reflections
Student Book An Introduction
.NET and .NET Core: Languages, Cloud, Mobile and AI
Lecture 9 Concepts of Programming Languages
C# Event Processing Model
6 Delegate and Lambda Expressions
Interface.
Conditional Statements
Classes & Objects: Examples
Inner Classes 29-Nov-18.
Fundaments of Game Design
Java Programming Language
Chengyu Sun California State University, Los Angeles
Lecture 9 Concepts of Programming Languages
Presentation transcript:

Delegates and Events Tom Roeder CS fa

Motivation – Function Pointers Treat functions as first-class objects eg. Scheme: (map myfunc somelist) works because functions are lists eg. Mathematica: {#, #^2} & Range[1,10] eg. C/C++: typedef int (*fptr)(int*); int my_method(int* var) { if (var != NULL) return *var; } fptr some_method = my_method; int take_f_param(fptr g) { int x = 10; int y = &x; return g(y); } printf(“%d\n”, take_f_param(some_method)); Works because functions are pointers to code

Motivation – Function Pointers Java no equivalent way to get function pointers use inner classes that contain methods or simply use interfaces Why not? functions are not objects same problem as integers

Comparators Sort method on many containers provides efficient sorting needs to be able to compare to objects Solution: IComparer public class ArrivalComparer: IComparer { public ArrivalComparer() {} public int Compare(object x, object y) { return ((Process)x).Arrival.CompareTo(((Process)y).Arrival); } } Can then call sortedList.Sort(new ArrivalComparer());

Delegates An objectified function inherits from System.Delegate sealed implicitly looks much like C/C++ style function pointer eg. delegate int Func(ref int x) defines a new type: Func: takes int, returns int declared like a function with an extra keyword stores a list of methods to call

Delegates – Example delegate int Func(ref int x); int Increment(ref int x) { return x++; } int Decrement(ref int x) { return x--; } Func F1 = new Func(Increment); F1 += Decrement; x = 10; Console.WriteLine(F1(ref x)); Console.WriteLine(x); Delegate calls methods in order ref values updated between calls return value is the value of the last call

Delegates – Usage Patterns Declared like a function Instantiated like a reference type takes a method parameter in the constructor Modified with +, -, +=, -= can add more than one instance of a method - removes the last instance of the method in the list Called like a function: functional programming

Delegates – Usage Examples delegate int Func(int x); List Map(Func d, List l) { List newL = new List (); foreach(int i in l) { newL.Add(d(l)); } return newL; } Allows code written in a more functional style

Notes on Delegates this pointer captured by instance delegates thus can capture temporary objects from method calls or elsewhere in delegates eg. delegate int Func(int x); Func f = new Func(); … { TempObject o = new TempObject(); f += o.m; } // o is now out of scope

Covariance & Contravariance If the type of the return value is subclass then the delegate is still acceptable called covariance If the type of the args are subclasses then the delegate is likewise acceptable called contravariance

Anonymous Methods Func f = new Func(); int y = 10; f += delegate(int x) { return x + y; } Creates a method and adds it to delegate treated the same as other methods good for one-time, short delegates Variables captured by anonymous method outer variables like y in the above example

Anonymous Methods using System; delegate void D(); class Test { static D[] F() { D[] result = new D[3]; for (int i = 0; i < 3; i++) { int x = i * 2 + 1; result[i] = delegate { Console.WriteLine(x); }; } return result; } static void Main() { foreach (D d in F()) d(); } }

Anonymous Methods static D[] F() { D[] result = new D[3]; int x; for (int i = 0; i < 3; i++) { x = i * 2 + 1; result[i] = delegate { Console.WriteLine(x); }; } return result; } First returns 1,3,5. Second returns 5,5,5 Outer variables are captured locations Not given values at delegate creation time Can communicate through outer variables

Events Special class of delegates given the event keyword class Room { public event EventHandler Enter; public void RegisterGuest(object source, EventArgs e) { … } public static void Main(string[] args) { Enter += new EventHandler(RegisterGuest); if (Enter != null) { Enter(this, new EventArgs()); } } }

Events Enter is an object of type delegate when event is “raised” each delegate called C# allows any delegate to be attached to an event.NET requires only EventHandlers needed for CLS compatibility Adds restrictions to the delegate can only raise an event in its defining class outside, can only do += and -= : return void

Events Modifiers on events public/private: define accessibility of += and -= Delegates cannot be defined in interfaces events can be defined in interfaces Since can only do += and -= outside, how do we raise events? normally with methods: eg. Button.OnClick sole purpose is to raise the event

Events – Accessors add and remove accessors can be explicitly defined for events use anonymous methods normally generated by compiler For example when want to control the space used for storage access the custom data structure in OnClick() or use to control accessibility

Events - Uses Registering callbacks common programming paradigm examples in OS and threaded code any asynchronous code does this Windowing code eg. Button.OnClick basis of Windows.Forms Handles the asynchrony of the user

Event-Based Programming Style of concurrent programming contrasts with thread based concurrency based on the number of events not on the number of processors although limited by number of processors events in C# could be backed by an event- based system full support for events already in language

Generics and Delegates Delegates can use generic parameters: delegate int Func (T t) allows interaction with generic classes class Test { public Test(Func f, T val) { … } Is the type Func open or closed? Methods can use delegates similarly Both can add where constraints like classes

Generics and Delegates Does the following work? delegate int F (int x); class Test2 where T : class where U : F { … } no: type constraints cannot be sealed classes can, however, change F to System.Delegate then we lose some ability to statically typecheck

Homework 2 - Polynomials Build a class that implements the polynomials polynomials in some abstract variables and further must be generic in their scalars only constraint: must have – and + is this possible?  What should be our solution? add methods to add, subtract, and multiply return Polynomials of same type add an indexer to get i-th term

Homework 3 – Sets Write a Set implements the union, intersection, and difference implements IEnumerable implements a Filter methods Questions?