Delegates and Events 14: Delegates and Events Programming C# © 2003 DevelopMentor, Inc. 12/1/2003
Objectives Introduce delegates and events defining delegate types invoking through delegates registering multiple targets Discuss design benefits of using delegates Programming C# © 2003 DevelopMentor, Inc. 12/1/2003
State Objects typically maintain state state changes over time 14: Delegates and Events State Objects typically maintain state state changes over time class Student { string name; double gpa; int units; public void RecordClass(int grade) gpa = (gpa * units + grade) / (units + 1); units++; } ... store state change state Programming C# © 2003 DevelopMentor, Inc. 12/1/2003
Notification May want to notify interested parties of state change 14: Delegates and Events Notification May want to notify interested parties of state change notification widely used throughout .NET framework user interface event handling most common example Parent RecordClass Student Registrar new grade causes gpa to change notify Programming C# © 2003 DevelopMentor, Inc. 12/1/2003
Pattern Notification typically involves registration and callback 14: Delegates and Events Pattern Notification typically involves registration and callback target registers with caller caller calls back target when state changes pattern also called publish/subscribe Student (caller) Parent (target) register callback Programming C# © 2003 DevelopMentor, Inc. 12/1/2003
14: Delegates and Events Delegates .NET Framework uses delegates to implement callbacks intermediary between caller and target declaration defines callback method signature instance stores object reference and method token caller target object target method callback delegate callback Programming C# © 2003 DevelopMentor, Inc. 12/1/2003
Information flow delegate 14: Delegates and Events Information flow Caller and target need to agree on information flow data passed through delegate Student Parent object Parent method double delegate double void void Programming C# © 2003 DevelopMentor, Inc. 12/1/2003
Delegate definition Define delegate with delegate keyword 14: Delegates and Events Delegate definition Define delegate with delegate keyword syntax similar to method declaration without body delegate name placed where method name usually goes delegate keyword name of delegate delegate void StudentCallback(double gpa); target method return type target method parameter Programming C# © 2003 DevelopMentor, Inc. 12/1/2003
Delegate as type Delegate name is type name can declare references 14: Delegates and Events Delegate as type Delegate name is type name can declare references can create objects define delegate delegate void StudentCallback(double gpa); StudentCallback a = new StudentCallback(...); reference object Programming C# © 2003 DevelopMentor, Inc. 12/1/2003
14: Delegates and Events Target use of delegate Target defines method with signature specified by delegate parameters and return type must match method name not constrained delegate defines required signature delegate void StudentCallback(double gpa); target class Parent { public void Report(double gpa) ... } method signature matches delegate Programming C# © 2003 DevelopMentor, Inc. 12/1/2003
Caller use of delegate Caller typically defines delegate reference 14: Delegates and Events Caller use of delegate Caller typically defines delegate reference caller class Student { public StudentCallback GpaChanged; ... } delegate reference Programming C# © 2003 DevelopMentor, Inc. 12/1/2003
Registration Create delegate object and store in caller to register 14: Delegates and Events Registration Create delegate object and store in caller to register pass target object and method to delegate constructor void Run() { Student ann = new Student("Ann"); Parent mom = new Parent(); StudentCallback a = new StudentCallback(mom.Report); ann.GpaChanged = a; ... } caller target create store target object target method Programming C# © 2003 DevelopMentor, Inc. 12/1/2003
Invocation Caller invokes callback indirectly through delegate 14: Delegates and Events Invocation Caller invokes callback indirectly through delegate uses method call syntax on delegate delegate calls target method on target object class Student { public StudentCallback GpaChanged; public void RecordClass(int grade) // update gpa ... GpaChanged(gpa); } invoke callback through delegate callback takes double argument Programming C# © 2003 DevelopMentor, Inc. 12/1/2003
Summary of delegate use 14: Delegates and Events Summary of delegate use define delegate delegate void StudentCallback(double gpa); class Parent { public void Report(double gpa) { ... } } class Student public StudentCallback GpaChanged; public void RecordClass(int grade) // update gpa ... GpaChanged(gpa); target method caller stores delegate caller invokes delegate Student ann = new Student("Ann"); Parent mom = new Parent(); ann.GpaChanged = new StudentCallback(mom.Report); ann.RecordClass(4); // 4 == 'A' create and install delegate Programming C# © 2003 DevelopMentor, Inc. 12/1/2003
Null reference Delegate is reference type 14: Delegates and Events Null reference Delegate is reference type defaults to null when used as field typical to guard invocation class Student { public StudentCallback GpaChanged; public void RecordClass(int grade) // update gpa ... if (GpaChanged != null) GpaChanged(gpa); } test before call Programming C# © 2003 DevelopMentor, Inc. 12/1/2003
Static methods Static method may be target of delegate 14: Delegates and Events Static methods Static method may be target of delegate use class name and method name when creating delegate no object specified since no this object associated with call class Registrar { public static void Log(double gpa) ... } static method void Run() { Student ann = new Student("Ann"); ann.GpaChanged = new StudentCallback(Registrar.Log); ... } register Programming C# © 2003 DevelopMentor, Inc. 12/1/2003
Multiple targets Can combine delegates using operator+= or operator+ 14: Delegates and Events Multiple targets Can combine delegates using operator+= or operator+ creates invocation list of delegates all targets called when delegate invoked targets called in order added use of += ok even when left-hand-side is null Parent mom = new Parent(); Parent dad = new Parent(); Student ann = new Student("Ann"); ann.GpaChanged += new StudentCallback(mom.Report); ann.GpaChanged += new StudentCallback(dad.Report); ... targets first second Programming C# © 2003 DevelopMentor, Inc. 12/1/2003
Remove delegate Can remove delegate from invocation list 14: Delegates and Events Remove delegate Can remove delegate from invocation list use operator-= or operator- identity of target object/method determines which is removed Parent mom = new Parent(); Parent dad = new Parent(); Student ann = new Student("Ann"); ann.GpaChanged += new StudentCallback(mom.Report); ann.GpaChanged += new StudentCallback(dad.Report); ... ann.GpaChanged -= new StudentCallback(dad.Report); add remove Programming C# © 2003 DevelopMentor, Inc. 12/1/2003
Public delegate Not common to have public delegate field 14: Delegates and Events Public delegate Not common to have public delegate field allows assignment: could overwrite existing registrants allows external invocation: decision should be made internally class Student { public StudentCallback GpaChanged; ... } public delegate Parent mom = new Parent(); Parent dad = new Parent(); Student ann = new Student("Ann"); ... ann.GpaChanged = new StudentCallback(mom.Report); ann.GpaChanged = new StudentCallback(dad.Report); ann.GpaChanged(4.0); overwrite mom handler invoke Programming C# © 2003 DevelopMentor, Inc. 12/1/2003
Events Events give private data/public accessor pattern for delegates 14: Delegates and Events Events Events give private data/public accessor pattern for delegates created by applying event keyword to delegate external code can uses += and -= no external assignment or invocation class Student { public event StudentCallback GpaChanged; ... } event Parent mom = new Parent(); Student ann = new Student("Ann"); ann.GpaChanged += new StudentCallback(mom.Report); ann.GpaChanged = new StudentCallback(mom.Report); ann.GpaChanged(4.0); ... ok to use += error to use = error to invoke Programming C# © 2003 DevelopMentor, Inc. 12/1/2003
Design delegate Delegates provide clean way to code publish/subscribe 14: Delegates and Events Design Delegates provide clean way to code publish/subscribe publisher independent of type of subscriber publisher independent of target method name subscriber constrained only by callback method signature promotes loosely coupled designs Publisher Subscriber target method publish delegate publish Programming C# © 2003 DevelopMentor, Inc. 12/1/2003
Summary Delegates are objects that invoke methods on other objects 14: Delegates and Events Summary Delegates are objects that invoke methods on other objects useful to implement callbacks Events add semantic/syntactic layer to delegates enforce clean and safe registration/deregistration protocols Programming C# © 2003 DevelopMentor, Inc. 12/1/2003