Delegates & Events 1.

Slides:



Advertisements
Similar presentations
Introduction to Web Application
Advertisements

Copyright © 2012 Pearson Education, Inc. Chapter 9 Delegates and 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.
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++
Class. 2 Objectives Discuss class basics –fields –methods –access levels Present object creation –new operator.
CS 2511 Fall  Abstraction Abstract class Interfaces  Encapsulation Access Specifiers Data Hiding  Inheritance  Polymorphism.
C# Event Processing Model Solving The Mystery. Agenda Introduction C# Event Processing Macro View Required Components Role of Each Component How To Create.
Java Methods By J. W. Rider. Java Methods Modularity Declaring methods –Header, signature, prototype Static Void Local variables –this Return Reentrancy.
Object Oriented Programming, Interfaces, Callbacks Delegates and Events Dr. Mike Spann
Programming Languages and Paradigms Object-Oriented Programming.
C++ Object Oriented 1. Class and Object The main purpose of C++ programming is to add object orientation to the C programming language and classes are.
REFACTORING Lecture 4. Definition Refactoring is a process of changing the internal structure of the program, not affecting its external behavior and.
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.
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.
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)
Chapter 6 Introduction to Defining Classes. Objectives: Design and implement a simple class from user requirements. Organize a program in terms of a view.
Object Oriented Programming.  Interface  Event Handling.
Module 8: Delegates and Events. Overview Delegates Multicast Delegates Events When to Use Delegates, Events, and Interfaces.
CIS162AD Inheritance Part 3 09_inheritance.ppt. CIS162AD2 Overview of Topics  Inheritance  Virtual Methods used for Overriding  Abstract Classes and.
Rina System development with Java Instructors: Rina Zviel-Girshin Lecture 4.
Inheritance. Inheritance - Introduction Idea behind is to create new classes that are built on existing classes – you reuse the methods and fields and.
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.
Special Features of C# : Delegates, Events and Attributes.
Events Programming in C# Events CSE 494R (proposed course for 459 Programming in C#) Prof. Roger Crawfis.
Quick Review of OOP Constructs Classes:  Data types for structured data and behavior  fields and methods Objects:  Variables whose data type is a class.
Effective C# 50 Specific Way to Improve Your C# Item 22, 23.
5.1 Basics of defining and using classes A review of class and object definitions A class is a template or blueprint for an object A class defines.
1.NETDelegates & eventsNOEA / PQC 2007 Delegates & events Observer pattern Delegates –Semantics –Cil – code –Usage Events Asynchronious delegates.
 ASP.NET provides an event based programming model that simplifies web programming  All GUI applications are incomplete without enabling actions  These.
Basic Class Structure. Class vs. Object class - a template for building an object –defines the instance data that the object will hold –defines instance.
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,
Topic: Classes and Objects
C# for C++ Programmers 1.
Chapter 9 Programming Based on Events
INF230 Basics in C# Programming
Delegates and Events Svetlin Nakov Telerik Corporation
Inheritance and Polymorphism
Delegates and Events 14: Delegates and Events
Methods Attributes Method Modifiers ‘static’
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.
Computing with C# and the .NET Framework
C# Event Processing Model
AVG 24th 2015 ADVANCED c# - part 1.
6 Delegate and Lambda Expressions
Java Programming Language
Subprograms and Programmer Defined Data Type
Object Oriented Practices
Lesson 7. Events, Delegates, Generics.
CIS16 Application Development and Programming using Visual Basic.net
Defining Classes and Methods
Programming in C# CHAPTER - 8
CIS 199 Final Review.
Defining Classes and Methods
DELEGATES AND EVENT MODELING
Object Oriented Programming
C++ Object Oriented 1.
Events, Delegates, and Lambdas
Presentation transcript:

Delegates & Events 1

Delegates Delegates are how C# defines a dynamic interface between two methods Same goal as function pointers in C Delegates are type-safe A delegate object holds a reference to a method with a pre-defined signature A signature is simply the argument list and return type of the method The keyword delegate specifies that we are defining a delegate object

Delegates Consists of two parts: a delegate type and a delegate instance A delegate type looks like an (abstract) method declaration, preceded with the delegate keyword A delegate instance creates an instance of this type, supplying it with the name of a real method to attach to

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 double and has a void return type delegate void MyDelegate(double d);

Instantiating a Delegate A Delegate Object Is Created with the new Operator Delegate Objects Are Immutable The method signature must match the delegate signature // instantiating a delegate to a static method Calculate // in the class MyClass MyDelegate a = new MyDelegate(MyClass.Calculate); // instantiating a delegate to an instance method // AMethod in object p MyClass p = new MyClass(); MyDelegate b = new MyDelegate(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 Calculate with the parameter 0.123 a(0.123);

Chaining (Multicast) Delegate Delegate objects can be initialized with several method calls using the += operator The method calls can then be invoked in a chain by passing the correct arguments to the delegate object Essentially it amounts to calling methods through a proxy object and is a powerful mechanism for event handling as we shall see Passing method calls into objects is then equivalent to passing delegate objects

Chaining (Multicast) Delegate A delegate instance is actually a container of callback functions. It can hold a list of values. The operators += and -= are defined to add and remove values. The operator = clears the list and assigns it to the rhs

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; //... }

Connecting to an Event An application can then register its interest in an event by adding an initialized delegate object to the event using the += operator // 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

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();

.NET Framework Guidelines 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;

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

Custom Event Example using System; namespace CustomEventExample { public delegate void ElapsedMinuteEventHandler(Object sender, MinuteEventArgs e); }

Custom Event Example using System; namespace CustomEventExample { public class MinuteEventArgs : EventArgs private DateTime date_time; public MinuteEventArgs(DateTime date_time) this.date_time = date_time; } public int Minute get { return date_time.Minute; }

Custom Event Example using System; namespace CustomEventExample { public class Publisher public event ElapsedMinuteEventHandler MinuteTick; public Publisher() { Console.WriteLine("Publisher Created"); } public void countMinutes() int current_minute = DateTime.Now.Minute; while (true) if (current_minute != DateTime.Now.Minute) Console.WriteLine("Publisher: {0}", DateTime.Now.Minute); onMinuteTick(new MinuteEventArgs(DateTime.Now)); current_minute = DateTime.Now.Minute; }//end if } // end countMinutes method public void onMinuteTick(MinuteEventArgs e) { if (MinuteTick != null) MinuteTick(this, e); } } // end Publisher class definition } // end CustomEventExample namespace

Custom Event Example using System; namespace CustomEventExample { public class Subscriber private Publisher publisher; public Subscriber(Publisher publisher) this.publisher = publisher; subscribeToPublisher(); Console.WriteLine("Subscriber Created"); } public void subscribeToPublisher() { publisher.MinuteTick += new ElapsedMinuteEventHandler(minuteTickHandler); } public void minuteTickHandler(Object sender, MinuteEventArgs e) { Console.WriteLine("Subscriber Handler Method: {0}", e.Minute); } } // end Subscriber class definition } // end CustomEventExample namespace

Custom Event Example using System; namespace CustomEventExample { public class MainApp public static void Main() Console.WriteLine("Custom Events are Cool!"); Publisher p = new Publisher(); Subscriber s = new Subscriber(p); p.countMinutes(); } // end main } //end MainApp class definition } // end CustomEventExample namespace

?

References