Chapter 9 Delegates and Events

Similar documents
Comp151. Definitions & Declarations

Storage Classes CS 110B - Rule Storage Classes Page 18-1 \handouts\storclas

Chapter 5 Functions. Introducing Functions

C++ INTERVIEW QUESTIONS

Calling the Function. Two Function Declarations Here is a function declared as pass by value. Why use Pass By Reference?

MAHALAKSHMI ENGINEERING COLLEGE B TIRUCHIRAPALLI

OBJECTIVE1: Understanding Windows Forms Applications

Visual Studio 2008 Express Editions

CpSc212 Goddard Notes Chapter 6. Yet More on Classes. We discuss the problems of comparing, copying, passing, outputting, and destructing

LAB4 Making Classes and Objects

Class 16: Function Parameters and Polymorphism

2009 Tutorial (DB4O and Visual Studio 2008 Express)

Java CPD (I) Frans Coenen Department of Computer Science

EP241 Computer Programming

Introduction to Object-Oriented Programming

Creating a Simple Visual C++ Program

Moving from CS 61A Scheme to CS 61B Java

Computer Programming C++ Classes and Objects 15 th Lecture

Sequential Program Execution

An Incomplete C++ Primer. University of Wyoming MA 5310

Install Java Development Kit (JDK) 1.8

Basics of I/O Streams and File I/O

Software Engineering 1 EEL5881 Spring Homework - 2

C++ Overloading, Constructors, Assignment operator

Formatting Numbers with C++ Output Streams

IS0020 Program Design and Software Tools Midterm, Feb 24, Instruction

Object Oriented Software Design II

Constructor, Destructor, Accessibility and Virtual Functions

You are to simulate the process by making a record of the balls chosen, in the sequence in which they are chosen. Typical output for a run would be:

Ch 7-1. Object-Oriented Programming and Classes

Using ilove SharePoint Web Services Workflow Action

C++FA 5.1 PRACTICE MID-TERM EXAM

Java Interview Questions and Answers

AP Computer Science Java Mr. Clausen Program 9A, 9B

13 Classes & Objects with Constructors/Destructors

Appendix K Introduction to Microsoft Visual C++ 6.0

Copyright 2001, Bill Trudell. Permission is granted to copy for the PLoP 2001 conference. All other rights reserved.

Object-Oriented Programming in Java

For the next three questions, consider the class declaration: Member function implementations put inline to save space.

Member Functions of the istream Class

CS193D Handout 06 Winter 2004 January 26, 2004 Copy Constructor and operator=

Visual C Tutorial

PART-A Questions. 2. How does an enumerated statement differ from a typedef statement?

Boolean Expressions, Conditions, Loops, and Enumerations. Precedence Rules (from highest to lowest priority)

PIC 10A. Lecture 7: Graphics II and intro to the if statement

CS170 Lab 11 Abstract Data Types & Objects

History OOP languages Year Language 1967 Simula Smalltalk

Chapter 3. Input and output. 3.1 The System class

Lecture 22: C Programming 4 Embedded Systems

CSI33 Data Structures

public static void main(string[] args) { System.out.println("hello, world"); } }

Objectif. Participant. Prérequis. Remarque. Programme. C# 3.0 Programming in the.net Framework. 1. Introduction to the.

MS Visual C++ Introduction. Quick Introduction. A1 Visual C++

Multichoice Quetions 1. Atributes a. are listed in the second part of the class box b. its time is preceded by a colon. c. its default value is

Introduction to the BackgroundWorker Component in WPF

Sources: On the Web: Slides will be available on:

Polymorphism. Problems with switch statement. Solution - use virtual functions (polymorphism) Polymorphism

AP Computer Science Java Subset

7.7 Case Study: Calculating Depreciation

The Java Series. Java Essentials I What is Java? Basic Language Constructs. Java Essentials I. What is Java?. Basic Language Constructs Slide 1

LAB 1. Familiarization of Rational Rose Environment And UML for small Java Application Development

C++ Crash Kurs. C++ Object-Oriented Programming

Developing an ODBC C++ Client with MySQL Database

The University of Alabama in Huntsville Electrical and Computer Engineering CPE Test #4 November 20, True or False (2 points each)

Data Structures using OOP C++ Lecture 1

Introduction to C++ Introduction to C++ Week 7 Dr Alex Martin 2013 Slide 1

2.2: Bitwise Logical Operations

Short Notes on Dynamic Memory Allocation, Pointer and Data Structure

See the Developer s Getting Started Guide for an introduction to My Docs Online Secure File Delivery and how to use it programmatically.

TABLE OF CONTENTS...2 INTRODUCTION...3 APPLETS AND APPLICATIONS...3 JAVABEANS...4 EXCEPTION HANDLING...5 JAVA DATABASE CONNECTIVITY (JDBC)...

Lecture 2 Notes: Flow of Control

C++ Input/Output: Streams

3.5. cmsg Developer s Guide. Data Acquisition Group JEFFERSON LAB. Version

1 bool operator==(complex a, Complex b) { 2 return a.real()==b.real() 3 && a.imag()==b.imag(); 4 } 1 bool Complex::operator==(Complex b) {

This loop prints out the numbers from 1 through 10 on separate lines. How does it work? Output:

Getting Started with the Internet Communications Engine

Java Classes. GEEN163 Introduction to Computer Programming

Exception Handling. Overloaded methods Interfaces Inheritance hierarchies Constructors. OOP: Exception Handling 1

CHAPTER 10: WEB SERVICES

Classes and Objects in Java Constructors. In creating objects of the type Fraction, we have used statements similar to the following:

Manual For Using the NetBeans IDE

Lab 7 Keyboard Event Handling Mouse Event Handling

CSE 1223: Introduction to Computer Programming in Java Chapter 2 Java Fundamentals

Konzepte objektorientierter Programmierung

JAVA - EXCEPTIONS. An exception can occur for many different reasons, below given are some scenarios where exception occurs.

C++ DATA STRUCTURES. Defining a Structure: Accessing Structure Members:

qwertyuiopasdfghjklzxcvbnmqwerty uiopasdfghjklzxcvbnmqwertyuiopasd fghjklzxcvbnmqwertyuiopasdfghjklzx cvbnmqwertyuiopasdfghjklzxcvbnmq

Microsoft Virtual Labs. Building Windows Presentation Foundation Applications - C# - Part 1

Function Overloading I

Crash Course in Java

Developing Task Model Applications

COSC 181 Foundations of Computer Programming. Class 6

How to create a SMTP plugin for ArGoSoft Mail Server,.NET edition (AMS.NET edition) using Visual Studio 2005

Description of Class Mutation Mutation Operators for Java

Topics. Parts of a Java Program. Topics (2) CS 146. Introduction To Computers And Java Chapter Objectives To understand:

INTRODUCTION TO COMPUTER PROGRAMMING. Richard Pierse. Class 7: Object-Oriented Programming. Introduction

How to create/avoid memory leak in Java and.net? Venkat Subramaniam

Transcription:

Chapter 9 Delegates and Events Two language features are central to the use of the.net FCL. We have been using both delegates and events in the topics we have discussed so far, but I haven t explored the inner workings or how to create your own delegates and events. In the next few sections I will do just that. Pointers to Functions To help C and C++ programmers to more easily understand the concept of delegates let's look at the use of pointers to functions in C++. This is the same technique you would use in C as well. Figure 9-1 shows a program that defines two simple functions, A and B, that merely output a line of text echoing the interg argument. The main function declares a pointer to a function, pf, that is a pointer to a function taking a single integer argument and doesn't return a value. The following line is this declaration: void (*pf)(int i); The pair or parenthesis around *pf are required. If the are omitted then the declaration merely declares a function that returns a pointer to void. That's not what we want. We can set pf to point to either A or B and then use pf as the function to call. Depending on whether it points to A or B the corresponding function will be called. The output is shown in Figure 9-2. #include <iostream> using namespace std; void A(int i) cout << "A called with " << i << endl; void B(int i) cout << "B called with " << i << endl; void main() void (*pf)(int i); pf=a; pf(1); pf=b; pf(2); return; Figure 9-1 1

Pointers to functions are often used as arguments to other functions such that they can utilize some arbitrary function specified by the argument. For example, we might define some type of data management tool that requires a comparison operation. By using a pointer to a function we could pass this pointer to the data management tool as an argument and it would use whatever function you wanted. The data management tool would not have to build in the name of the comparison function. Building in the name of the function would also mena that we would have to have several versions of this tool, one for each different comparison function you wrote. The.NET FCL actually uses this very technique with its collection classes. Of course a delegate is used since pointers are available only with unmanaged code and we want to avoid that if at all possible. Let's focus our attention on delegates and how they provide the same capabilities as pointers to functions with some added features as well. Figure 9-2 The Delegate Equivalent A delegate is declared by prefacing the signature for a method with the keyword delegate. A delegate can be declared with global scope or local to a class. Making it global allows it to be used by many different classes without tying it to one class in particular. This is similar to the way we usually use enumerations in the.net FCL. The following line declares a delegate to a method taking on integer argument and not returning a value: delegate void mydelegate(int i); In order to use the delegate to call a method we need to create an instance of the delegate and associate it with a particular method. The method may be a static or instance method. It makes no difference. By the way, this is a very significant improvement over pointers to functions. In C++ it is tricky to use pointer to functions that are associated with the instance of a class. The following four lines show how we can create a delegate associated with method A, call it, associate a new instance of the delegate with method B, and finally call that method: 2

mydelegate md = new mydelegate(a); md(1); md = new mydelegate(b); The complete program is shown in Figure 9-3. As you might expect, the output when we run this program is identical to that of the previous C++ example. DelegateEx1 using System; using System.Collections.Generic; using System.Text; namespace DelegateEx1 delegate void mydelegate(int i); class Program static void A(int i) Console.WriteLine("A called with 0", i); static void B(int i) Console.WriteLine("B called with 0", i); static void Main(string[] args) mydelegate md = new mydelegate(a); md(1); md = new mydelegate(b); Figure 9-3 Multicasting A feature of delegates that is not possible with pointers to functions is multicasting. Multicasting is a feature that allows more than one method to be associated with a delegate instance. The += operator is used to add additional methods. If we replace the four lines of code discussed above with the following three lines we get the output shown in Figure 9-4: mydelegate md = new mydelegate(a); md += new mydelegate(b); Notice that one call to md invokes both methods A and B. We can use the -=operator to remove a method from the delegate list. However, this requires that 3

we use a named instance in order to identify the instance we want. We might do something like this: mydelegate md = new mydelegate(a); mydelegate del2 = new mydelegate(b); md += del2; md(1); md -= del2; //removes the delegate The second call to md would output "A called with 2." Figure 9-4 Events We have been using the built-in events of the FCL such as for a mouse click or menu item. You can declare your own events and use them in the same way. An event is really just a delegate with a very specific prototype: Delegate void MyEvent(object sender, MyEventArgs e); This is actually a convention and not mandatory. sender refers to the class that is triggering the event. The second argument, e, is an object derived from System.EventArgs. and allows arbitrary information to be passed to the recipient event handler. Adding the event keyword to a delegate instance ensures that only the += and -= operators will be used outside the class that declares the event. This prevents the accidental overwriting of handlers that are already assigned to the delegate. Consider using the mouse click event. We can only add or remove a specific handler and not eliminate all existing handlers by the accidental use of the assignment operator. Furthermore, an event can only be triggered from within the class that defines it. We need to provide a method to trigger the event. The Control class defines the following click event: public event EventHandler Click; 4

When we add an event handler for this event manually or using the designer we are adding our handler to any that already exist. Normally this event is triggered by the operating system when you click the mouse. However, you can call a method in the Control class to programmatically trigger this event. protected void InvokeOnClick ( Control toinvoke, EventArgs e ) This is a protected method and therefore only be used by classes derived from Control. Of course any method in your form class can call it since Form is derived from Control. This is just an example and a trigger method for an event can just as well be public. Our previous example can be rewritten using an event as shown in Figures Figure 9-5 and Figure 9-6. EventHanderl1 using System; using System.Collections.Generic; using System.Text; using System.IO; namespace EventHandler1 public delegate void myevent(object sender, MyEventArgs e); class MyEventArgs : EventArgs public int i; class Program public event myevent me; static void Main(string[] args) (new Program()).Run(); void Run() MyEventArgs e = new MyEventArgs(); e.i = 1; me = new myevent(a); Trigger(this, e); (new tryevent(this)).addevent(); public void Trigger(object sender, MyEventArgs e) me(sender, e); //triger the event void A(object sender, MyEventArgs e) 5

Console.WriteLine("A called with 0", e.i); class tryevent Program p; public tryevent(program p) this.p = p; public void addevent() MyEventArgs e = new MyEventArgs(); e.i = 2; p.me += new myevent(b); //the next statement would fail if compiled //p.me = new myevent(b); p.trigger(this, e); //trigger the event void B(object sender, MyEventArgs e) Console.WriteLine("B called with 0", e.i); Figure 9-5 Figure 9-6 Since we need to pass an argument to the event handlers A and B I have declared my own class derived from EventArgs. It includes a field for the value i. The delegate myevent is used to declare an event handler. The actual event is declared as myevent me and is a public field in the Program class. Since I didn t want to make everything static I instantiate the Program class and call the Run method that does all the work. Run first creates a new MyEventArgs object and sets i to one. Method A is added to the event me. Run then triggers the event by calling the public method Trigger. All Trigger does is in invoke the event me. To demonstrate how another class could add its own event handler to the event and then trigger it, I wrote the tryevent class. Its constructor is passed a 6

reference to the Program class instance. The addevent method adds the event handle B to the me event and triggers the event. What is important to note is that you can only add the event handler using the += operator. If you try to replace the chain of existing event handlers using an assignment the compiler would generate an error. All this is the result of using the event leyword. If you were to remove the event keyword and uncomment the assignment the compiler would not complain. So you see, events are really just delegates with a recommended signature and a mechanism to safeguard accidentally replacing all the handlers by assignment. The FCL contains a declaration for a generic event handler that does not require custom event arguments. In that case you can use it without declaring your own custom delegate. public delegate void EventHandler(object sender, EventArgs e); 7