Module 8: Delegates and Events. Overview Delegates Multicast Delegates Events When to Use Delegates, Events, and Interfaces.

Slides:



Advertisements
Similar presentations
Introduction to Web Application
Advertisements

Module 12: Operators, Delegates, and Events. Overview Introduction to Operators Operator Overloading Creating and Using Delegates Defining and Using Events.
Composition CMSC 202. Code Reuse Effective software development relies on reusing existing code. Code reuse must be more than just copying code and changing.
Delegates and lambda functions Jim Warren, COMPSCI 280 S Enterprise Software Development.
CS  C++ Function Pointers  C# Method References  Groundwork for Lambda Functions.
Remote Method Invocation Chin-Chih Chang. Java Remote Object Invocation In Java, the object is serialized before being passed as a parameter to an RMI.
Programming Based on Events
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++
Writing Object Oriented Software with C#. C# and OOP C# is designed for the.NET Framework  The.NET Framework is Object Oriented In C#  Your access to.
Java CourseWinter 2009/10. Introduction Object oriented, imperative programming language. Developed: Inspired by C++ programming language.
Programming Handheld and Mobile devices 1 Programming of Handheld and Mobile Devices Lecture 20 Microsoft’s Approach 3 – C# Rob Pooley
C# Event Processing Model Solving The Mystery. Agenda Introduction C# Event Processing Macro View Required Components Role of Each Component How To Create.
Differences between C# and C++ Dr. Catherine Stringfellow Dr. Stewart Carpenter.
C# vs. C++ What's Different & What's New. An example C# public sometype myfn { get; set; } C++ public: sometype myfn { sometype get (); void set (sometype.
Programming Languages and Paradigms Object-Oriented Programming.
Copyright © 2003 ProsoftTraining. All rights reserved. Distributed Object Computing Using Java and CORBA.
Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Taken from slides of Starting Out with C++ Early Objects Seventh Edition.
Introduction to Object Oriented Programming. Object Oriented Programming Technique used to develop programs revolving around the real world entities In.
Delegates and lambda functions Jim Warren, COMPSCI 280 S Enterprise Software Development.
An Introduction to Java Chapter 11 Object-Oriented Application Development: Part I.
Module 3: Working with Components. Overview An Introduction to Key.NET Framework Development Technologies Creating a Simple.NET Framework Component Creating.
Delegates Programming in C# Delegates CSE 494R (proposed course for 459 Programming in C#) Prof. Roger Crawfis.
Tuc Goodwin  Object and Component-Oriented Programming  Classes in C#  Scope and Accessibility  Methods and Properties  Nested.
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.
ILM Proprietary and Confidential -
An Object-Oriented Approach to Programming Logic and Design Chapter 3 Using Methods and Parameters.
Chapter 6 Introduction to Defining Classes. Objectives: Design and implement a simple class from user requirements. Organize a program in terms of a view.
A Quick CCM Example. Tutorial on CCM Introduction A Simple Sender&Receiver Scenario Sender sends out the click-out event to inform the Receiver. Receiver.
Neal Stublen Tonight’s Agenda  Indexers  Delegates and events  Operator overloading  Class inheritance  Q&A.
Chapter 8 Class Inheritance and Interfaces F Superclasses and Subclasses  Keywords: super F Overriding methods  The Object Class  Modifiers: protected,
Application development with Java Lecture 21. Inheritance Subclasses Overriding Object class.
Introduction to Object-Oriented Programming Lesson 2.
1.NETDelegates & eventsNOEA / PQC Delegates & events Observer pattern Delegates –Semantics –Cil – kode –Anvendelse Events.
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.
Special Features of C# : Delegates, Events and Attributes.
CS212: Object Oriented Analysis and Design Lecture 22: Generic Class Design.
Presented by Ted Higgins, SQL Server DBA An Introduction to Object – Oriented Programming.
© 2006 Pearson Addison-Wesley. All rights reserved 1-1 Chapter 1 Review of Java Fundamentals.
Polymorphism and Virtual Functions One name many shapes behaviour Unit - 07.
1.NETDelegates & eventsNOEA / PQC 2007 Delegates & events Observer pattern Delegates –Semantics –Cil – kode –Anvendelse Events.
Module 13: Properties and Indexers. Overview Using Properties Using Indexers.
1.NETDelegates & eventsNOEA / PQC 2007 Delegates & events Observer pattern Delegates –Semantics –Cil – code –Usage Events Asynchronious delegates.
Arrays & Enum & Events. Arrays Arrays are data structures consisting of related data items of the same type. Arrays are fixed-length entities—they remain.
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 –
Basic Class Structure. Class vs. Object class - a template for building an object –defines the instance data that the object will hold –defines instance.
Module 5: Programming with C#. Overview Using Arrays Using Collections Using Interfaces Using Exception Handling Using Delegates and Events.
Chapter 5 Introduction to Defining Classes Fundamentals of Java.
Inheritance Modern object-oriented (OO) programming languages provide 3 capabilities: encapsulation inheritance polymorphism which can improve the design,
C# for C++ Programmers 1.
INF230 Basics in C# Programming
Delegates and Events Svetlin Nakov Telerik Corporation
2.7 Inheritance Types of inheritance
Module 5: Common Type System
Delegates and Events 14: Delegates and Events
Chapter 3: Using Methods, Classes, and Objects
Chapter Eleven Handling Events.
Array Array is a variable which holds multiple values (elements) of similar data types. All the values are having their own index with an array. Index.
.NET and .NET Core: Languages, Cloud, Mobile and AI
C# In many ways, C# looks similar to Java
C# Event Processing Model
AVG 24th 2015 ADVANCED c# - part 1.
6 Delegate and Lambda Expressions
Delegates & Events 1.
Lesson 7. Events, Delegates, Generics.
Programming in C# CHAPTER - 8
CIS 199 Final Review.
Class.
Chengyu Sun California State University, Los Angeles
Events, Delegates, and Lambdas
Presentation transcript:

Module 8: Delegates and Events

Overview Delegates Multicast Delegates Events When to Use Delegates, Events, and Interfaces

 Delegates Delegate Scenario Declaring a Delegate Instantiating a Delegate Calling a Delegate

Delegate Scenario 1 - Change in switch position invokes switch’s OnFlip method 2 - OnFlip Method invokes delegate 3 - Delegate invokes light’s OnFlipCallback method 4 - OnFlipCallback method changes light’s state OnFlip method Switch Object OnFlipCallback method Light Object Delegate object OnFlip method Switch Object

Declaring a Delegate A Delegate Declaration Defines a Type That Encapsulates a Method with a Particular Set of Arguments and Return Type // declares a delegate for a method that takes a single // argument of type string and has a void return type delegate void MyDelegate1(string s); // declares a delegate for a method that takes a single // argument of type string and has a void return type delegate void MyDelegate1(string s);

Instantiating a Delegate A Delegate Object Is Created with the new Operator Delegate Objects Are Immutable // instantiating a delegate to a static method Hello // in the class MyClass MyDelegate1 a = new MyDelegate1(MyClass.Hello); // instantiating a delegate to an instance method // AMethod in object p MyClass p = new MyClass(); MyDelegate1 b = new MyDelegate1(p.AMethod); // instantiating a delegate to a static method Hello // in the class MyClass MyDelegate1 a = new MyDelegate1(MyClass.Hello); // instantiating a delegate to an instance method // AMethod in object p MyClass p = new MyClass(); MyDelegate1 b = new MyDelegate1(p.AMethod);

Calling a Delegate Use a Statement Containing: The name of the delegate object Followed by the parenthesized arguments to be passed to the delegate // given the previous delegate declaration and // instantiation, the following invokes MyClass ' // static method Hello with the parameter "World" a("World"); // given the previous delegate declaration and // instantiation, the following invokes MyClass ' // static method Hello with the parameter "World" a("World");

Demonstration: Using Delegates

 Multicast Delegates Multicast Delegate Scenario Single vs. Multicast Delegates Creating and Invoking Multicast Delegates C# Language-Specific Syntax Delegate Details

Multicast Delegate Scenario 2 - OnFlip method invokes multicast delegate1 4 - OnFlipCallback method changes light1’s state 3 - delegate1 invokes light1’s OnFlipCallback 7 - OnFlipCallback method changes light2’s state 6 - delegate2 invokes light2’s OnFlipCallback OnFlip method Switch Object OnFlipCallback method Light1 Object OnFlipCallback method Light2 Object Multicast delegate1 object Multicast delegate2 object Invocation list 5 - delegate2 is invoked 1 - Change in switch position invokes switch’s OnFlip method OnFlip method Switch Object

Single vs. Multicast Delegates All Delegates Have an Invocation List of Methods That Are Executed When Their Invoke Method is Called Single-Cast Delegates: Derived Directly From System.Delegate Invocation list contains only one method Multicast Delegates: Derived from System.MulticastDelegate Invocation list may contain multiple methods Multicast delegates contain two static methods to add and remove references from invocation list: Combine and Remove Use GetInvocationList to Obtain an Invocation List as an Array of Delegate References Use a Delegate’s Target and Method Properties to Determine: Which object will receive the callback Which method will be called

Creating and Invoking Multicast Delegates // assign to c the composition of delegates a and b c = (MyDelegate2)Delegate.Combine(a, b); // assign to d the result of removing a from c d = (MyDelegate2)Delegate.Remove(c, a); // Iterate through c's invocation list // and invoke all delegates except a Delegate[] DelegateList = c.GetInvocationList(); for (int i = 0; i < DelegateList.Length; i++) { if (DelegateList[i].Target != aFoo1) { ((MyDelegate2) DelegateList[i])(); } // assign to c the composition of delegates a and b c = (MyDelegate2)Delegate.Combine(a, b); // assign to d the result of removing a from c d = (MyDelegate2)Delegate.Remove(c, a); // Iterate through c's invocation list // and invoke all delegates except a Delegate[] DelegateList = c.GetInvocationList(); for (int i = 0; i < DelegateList.Length; i++) { if (DelegateList[i].Target != aFoo1) { ((MyDelegate2) DelegateList[i])(); }

C# Language-Specific Syntax C# Delegates That Return Void Are Multicast Delegates In C#, Use the + and - Operators to Add and Remove Invocation List Entries Less verbose than Combine and Remove methods MyDelegate a, b, c, d; a = new MyDelegate(Foo); b = new MyDelegate(Bar); c = a + b; // Compose two delegates to make another d = c - a; // Remove a from the composed delegate a += b;// Add delegate b to a ' s invocation list a -= b;// Remove delegate b from a ' s list MyDelegate a, b, c, d; a = new MyDelegate(Foo); b = new MyDelegate(Bar); c = a + b; // Compose two delegates to make another d = c - a; // Remove a from the composed delegate a += b;// Add delegate b to a ' s invocation list a -= b;// Remove delegate b from a ' s list

Demonstration: Multicast Delegates

Delegate Details A Delegate Declaration Causes the Compiler to Generate a New Class // delegate void MyDelegate3(string val); class MyDelegate3 : System.MulticastDelegate { public MyDelegate3(object obj, methodref mref) : base (obj, mref) { //... } public void virtual Invoke(string val) { //... } }; // delegate void MyDelegate3(string val); class MyDelegate3 : System.MulticastDelegate { public MyDelegate3(object obj, methodref mref) : base (obj, mref) { //... } public void virtual Invoke(string val) { //... } };

 Events Declaring an Event Connecting to an Event Raising an Event.NET Framework Guidelines

Declaring an Event Declare the Delegate Type for the Event Declare the Event Like the field of delegate type preceded by an event keyword // MouseClicked delegate declared public delegate void MouseClickedEventHandler(); public class Mouse { // MouseClicked event declared public static event MouseClickedEventHandler MouseClickedHandler; //... } // MouseClicked delegate declared public delegate void MouseClickedEventHandler(); public class Mouse { // MouseClicked event declared public static event MouseClickedEventHandler MouseClickedHandler; //... }

Connecting to an Event Connect by Combining Delegates Disconnect by Removing Delegates // Client’s method to handle the MouseClick event private void MouseClicked() { //... } //... // Client code to connect to MouseClicked event Mouse.MouseClickedHandler += new MouseClickedEventHandler(MouseClicked); // Client code to break connection to MouseClick event Mouse.MouseClickedHandler -= new MouseClickedEventHandler(MouseClicked); // Client’s method to handle the MouseClick event private void MouseClicked() { //... } //... // Client code to connect to MouseClicked event Mouse.MouseClickedHandler += new MouseClickedEventHandler(MouseClicked); // Client code to break connection to MouseClick event Mouse.MouseClickedHandler -= new MouseClickedEventHandler(MouseClicked);

Raising an Event Check Whether Any Clients Have Connected to This Event If the event field is null, there are no clients Raise the Event by Invoking the Event’s Delegate if (MouseClickedHandler != null) MouseClickedHandler(); if (MouseClickedHandler != null) MouseClickedHandler();

Name Events with a Verb and Use Pascal Casing Use "Raise" for Events, Instead of "Fire" Event Argument Classes Extend System.EventArgs Event Delegates Return Void and Have Two Arguments Use a Protected Virtual Method to Raise Each Event public class SwitchFlippedEventArgs : EventArgs { //... } public delegate void SwitchFlippedEventHandler( object sender, SwitchFlippedEventArgs e); public event SwitchFlippedEventHandler SwitchFlippedHandler; public class SwitchFlippedEventArgs : EventArgs { //... } public delegate void SwitchFlippedEventHandler( object sender, SwitchFlippedEventArgs e); public event SwitchFlippedEventHandler SwitchFlippedHandler;.NET Framework Guidelines

When to Use Delegates, Events, and Interfaces Use a Delegate If: You basically want a C-style function pointer You want single callback invocation The callback should be registered in the call or at construction time, not through methods Use Events If: Client signs up for the callback function through methods More than one object will care Use an Interface If: The callback function entails complex behavior, such as multiple methods

Lab 8: Creating a Simple Chat Server

Review Delegates Multicast Delegates Events When to Use Delegates, Events, and Interfaces