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

Slides:



Advertisements
Similar presentations
Introduction to Web Application
Advertisements

pa 1 Porting BETA to ROTOR ROTOR Projects Presentation Day, June by Peter Andersen.
CHARLES UNIVERSITY IN PRAGUE faculty of mathematics and physics C# Language &.NET Platform 12 th -13 th Lecture Pavel Ježek.
Static Members, Structures, Enumerations, Generic Classes, Namespaces Learning & Development Team Telerik Software Academy.
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.
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.
1 Generics and Using a Collection Generics / Parameterized Classes Using a Collection Customizing a Collection using Inheritance Inner Classes Use of Exceptions.
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
Building Java Programs Inner classes, generics, abstract classes reading: 9.6, 15.4,
ASP.NET Programming with C# and SQL Server First Edition
Templates. Objectives At the conclusion of this lesson, students should be able to Explain how function templates are used Correctly create a function.
Delegates and Events Tom Roeder CS fa. Motivation – Function Pointers Treat functions as first-class objects eg. Scheme: (map myfunc somelist)
Abstract Data Types and Encapsulation Concepts
 2006 Pearson Education, Inc. All rights reserved Generics.
Like our natural language. Designed to facilitate the expression and communication ideas between people and computer Like our natural language. Designed.
Differences between C# and C++ Dr. Catherine Stringfellow Dr. Stewart Carpenter.
Singleton Christopher Chiaverini Software Design & Documentation September 18, 2003.
COMP 205 – Week 10 Chunbo Chu. Method Local variables The existence of a local variable is limited to the block in which it is created and the blocks.
Chapter 2: Everything is an Object ● C++ has many non object oriented features inherited from C. It is a hybrid language meaning that it support different.
An Introduction to Java Chapter 11 Object-Oriented Application Development: Part I.
1 Generics and Using a Collection Generics / Parameterized Classes Using a Collection Customizing a Collection using Inheritance Inner Classes Use of Exceptions.
Hoang Anh Viet Hà Nội University of Technology Chapter 1. Introduction to C# Programming.
1 SystemVerilog Enhancement Requests Daniel Schostak Principal Engineer February 26 th 2010.
Chapter 10 Defining Classes. The Internal Structure of Classes and Objects Object – collection of data and operations, in which the data can be accessed.
1 Interfaces and Abstract Classes Chapter Objectives You will be able to: Write Interface definitions and class definitions that implement them.
Chapter 6 Introduction to Defining Classes. Objectives: Design and implement a simple class from user requirements. Organize a program in terms of a view.
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.
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. Chapter 26 - Java Object-Based Programming Outline 26.1Introduction.
Design Patterns Software Engineering CS 561. Last Time Introduced design patterns Abstraction-Occurrence General Hierarchy Player-Role.
Chapter 7: Class Inheritance F Superclasses and Subclasses F Keywords: super and this F Overriding methods F The Object Class F Modifiers: protected, final.
Introduction to Object-Oriented Programming Lesson 2.
CSCI 3328 Object Oriented Programming in C# Chapter 9: Classes and Objects: A Deeper Look – Exercises 1 Xiang Lian The University of Texas Rio Grande Valley.
Interfaces and Inner Classes
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.
1 Chapter 11 © 1998 by Addison Wesley Longman, Inc The Concept of Abstraction - The concept of abstraction is fundamental in programming - Nearly.
1 Copyright © 1998 by Addison Wesley Longman, Inc. Chapter 10 Abstraction - The concept of abstraction is fundamental in programming - Nearly all programming.
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All rights reserved. 1 Chapter 15 Event-Driven Programming and.
Singleton Pattern. Problem Want to ensure a single instance of a class, shared by all uses throughout a program Context Need to address initialization.
V 1.0 OE-NIK HP 1 Advanced Programming Delegates, Events.
Object Oriented Programming in Java Habib Rostami Lecture 10.
UMass Lowell Computer Science Java and Distributed Computing Prof. Karen Daniels Fall, 2000 Lecture 10 Java Fundamentals Objects/ClassesMethods.
Object Based Programming Chapter 8. 2 Contrast ____________________ Languages –Action oriented –Concentrate on writing ________________ –Data supports.
C# for C++ Programmers 1.
Examples of Classes & Objects
Delegates and Events 14: Delegates and Events
.NET and .NET Core: Languages, Cloud, Mobile and AI
Corresponds with Chapter 7
6 Delegate and Lambda Expressions
Classes & Objects: Examples
Inner Classes 29-Nov-18.
CSE 1030: Implementing GUI Mark Shtern.
Programming in C# CHAPTER - 8
Outline Anatomy of a Class Encapsulation Anatomy of a Method
Java Programming Language
Inner Classes 11-May-19.
Inner Classes 18-May-19.
Chengyu Sun California State University, Los Angeles
Threads and concurrency / Safety
Presentation transcript:

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

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

Questions?