Presentation is loading. Please wait.

Presentation is loading. Please wait.

Delegates and Events Callback Functionality and Event-Driven Programming Svetlin Nakov Technical Trainer Software University

Similar presentations


Presentation on theme: "Delegates and Events Callback Functionality and Event-Driven Programming Svetlin Nakov Technical Trainer Software University"— Presentation transcript:

1 Delegates and Events Callback Functionality and Event-Driven Programming Svetlin Nakov Technical Trainer www.nakov.com Software University http://softuni.bg

2 2 1.What are Delegates?1.What are Delegates? 2.Generic Delegates2.Generic Delegates  Action and Func  Action and Func 3.Anonymous Methods3.Anonymous Methods 4.Predicates4.Predicates 5.Events and Event Handlers5.Events and Event Handlers  Events vs. Delegates Table of Contents

3 What are Delegates?What are Delegates?

4 4  Delegates are special C# types that hold a method reference  A data type holding a function (method) as its value  Describe the parameters accepted and return value (method signature)  Delegates are similar to function pointers in C and C++  Strongly-typed pointer (reference) to a method  Pointer (address) to a callback function  In JavaScript any variable can hold a function  In C# only variable of type delegate can hold a function What are Delegates?What are Delegates?

5 5  Can point to static and instance methods  Can point to a sequence of multiple methods  Used to perform callbacks invocations  Used to implement the "publish-subscribe" model  Components publish their events  E.g. Button publish Click and MouseOver events  Other components subscribe to events  E.g. LoginForm subscribes to LoginButton.Click What are Delegates? (2)What are Delegates? (2)

6 6 Delegates – ExampleDelegates – Example // Declaration of a delegate public delegate void SimpleDelegate(string param); public class DelegatesExample { public static void TestMethod(string param) public static void TestMethod(string param) { Console.WriteLine("I was called by a delegate."); Console.WriteLine("I was called by a delegate."); Console.WriteLine("I got parameter {0}.", param); Console.WriteLine("I got parameter {0}.", param); } public static void Main() public static void Main() { // Instantiate the delegate // Instantiate the delegate SimpleDelegate d = new SimpleDelegate(TestMethod); SimpleDelegate d = new SimpleDelegate(TestMethod); // Invocation of the method, pointed by delegate // Invocation of the method, pointed by delegate d("test"); d("test"); }}

7 Simple DelegateSimple Delegate Live Demo

8 8 Delegates are MulticastDelegates are Multicast delegate int StringDelegate (T value); public class MultiDelegates { static int PrintString(string str) static int PrintString(string str) { Console.WriteLine("Str: {0}", str); Console.WriteLine("Str: {0}", str); return 1; return 1; } int PrintStringLength(string value) int PrintStringLength(string value) { Console.WriteLine("Length: {0}", value.Length); Console.WriteLine("Length: {0}", value.Length); return 2; return 2; } public static void Main() public static void Main() { StringDelegate d = MultiDelegates.PrintString; StringDelegate d = MultiDelegates.PrintString; d += new MultiDelegates().PrintStringLength; d += new MultiDelegates().PrintStringLength; int result = d("some string value"); int result = d("some string value"); Console.WriteLine("Returned result: {0}", result); Console.WriteLine("Returned result: {0}", result); }}

9 Multicast DelegatesMulticast Delegates Live Demo

10 10  A delegate can be generic:  C# has a feature called implicit method group conversion  Applies to all delegate types  Enables you to write the previous line with this simplified syntax: Generic DelegatesGeneric Delegates public delegate void SomeDelegate (T item); public static void Notify(int i) { } SomeDelegate d = new SomeDelegate (Notify); SomeDelegate d = Notify;

11 11  Predefined delegates in.NET:  Action – generic predefined void delegate  Func – generic predefined delegate with return value of type TResult  Examples: Predefined Delegates: Action and FuncPredefined Delegates: Action and Func Func intParseFunction = int.Parse; int num = intParseFunction("10"); Action printNumberAction = Console.WriteLine; printNumberAction(num);

12 Action and Func Action and Func Live Demo

13 Anonymous MethodsAnonymous Methods Definition and Parameters

14 14  Often a class / method is created just for the sake of using a delegate  The code involved is often relatively short and simple  Anonymous methods let you define a nameless method called by a delegate  Lambda functions are a variant of anonymous methods with shorter syntax Anonymous MethodsAnonymous Methods

15 class InvokeDelegateExample { static void SomeMethod(string msg) static void SomeMethod(string msg) { Console.WriteLine(msg); Console.WriteLine(msg); } static void Main() static void Main() { Action action = SomeMethod; Action action = SomeMethod; action(); action(); }} 15 Delegates: The Standard WayDelegates: The Standard Way A delegate holds a method as its value

16 class AnnonymousMethodExample { static void Main() static void Main() { Action action = delegate(string msg) Action action = delegate(string msg) { MessageBox.Show(msg); MessageBox.Show(msg); }; }; action(); action(); }} 16 Using Anonymous MethodsUsing Anonymous Methods A delegate holds an anonymous method as its value

17 17 Using Lambda ExpressionUsing Lambda Expression class LambdaExpressionExample { static void Main() static void Main() { Action action = ((msg) => Action action = ((msg) => { MessageBox.Show(msg); MessageBox.Show(msg); }); }); action(); action(); }} A delegate holds a lambda function as its value

18 Anonymous MethodsAnonymous Methods Live Demo

19 Predicates Predefined Boolean Delegates

20 20  Predicates are predefined delegates with the following signature  Define a way to check if an object meets some Boolean criteria  Used by many methods in Array and List to search for an element  For example IList.FindAll(Predicate ) retrieves all elements meeting the criteria, defined by the predicate Predicates public delegate bool Predicate (T obj)

21 21 Predicates – ExamplePredicates – Example List towns = new List () { "Sofia", "Burgas", "Plovdiv", "Varna", "Sofia", "Burgas", "Plovdiv", "Varna", "Ruse", "Sopot", "Silistra" "Ruse", "Sopot", "Silistra"}; List townsWithS = towns.FindAll(delegate(string town) towns.FindAll(delegate(string town) { return town.StartsWith("S"); return town.StartsWith("S"); }); }); foreach (string town in townsWithS) { Console.WriteLine(town); Console.WriteLine(town);}

22 Predicates Live Demo

23 Events

24 24  In component-oriented programming components publish events to the other components  Events notify about something happened  E.g. moving the mouse causes an event  The object which causes an event is called event sender  The object which receives an event is called event receiver  In order to receive an event, the event receivers should first " subscribe for the event "  In order to receive an event, the event receivers should first "subscribe for the event" Events

25 25  Events in C# are special delegate instances declared by the keyword event  In the component model of.NET the  subscription  sending  receiving of events is supported through delegates and eventsof events is supported through delegates and events Events in.NETEvents in.NET public event SomeDelegate eventName;

26 26  The C# compiler automatically defines the += and -= operators for events  += subscribes for an event  -= unsubscribes for an event  No other operations are allowed  Events can redefine the code for subscription and unsubscription Events in.NET (2)Events in.NET (2)

27 27  Events are not the same as member fields of type delegate  Events can be members of an interface  Delegates cannot  An event can only be called in the class where it is defined  By default the access to the events is synchronized (thread-safe) Events vs. DelegatesEvents vs. Delegates public Action m; ≠ public event Action m;

28 28  System.EventHandler defines a reference to a callback method, which handles events  No additional information is sent about the event, just a notification:  Used in many occasions internally in.NET  The EventArgs class is the base class with no information for the event The System.EventHandler DelegateThe System.EventHandler Delegate public delegate void EventHandler(Object sender, EventArgs e);

29 29 The System.EventHandler Delegate (2)The System.EventHandler Delegate (2) public class Button { public event EventHandler Click; public event EventHandler Click; public event EventHandler GotFocus; public event EventHandler GotFocus; public event EventHandler TextChanged; public event EventHandler TextChanged;......} public class ButtonExample { private static void OnButtonClick(object sender, private static void OnButtonClick(object sender, EventArgs eventArgs) EventArgs eventArgs) { Console.WriteLine("OnButtonClick() event called."); Console.WriteLine("OnButtonClick() event called."); } public static void Main() public static void Main() { Button button = new Button(); Button button = new Button(); button.Click += new EventHandler(OnButtonClick); button.Click += new EventHandler(OnButtonClick); }}

30 The System.EventHandler DelegateThe System.EventHandler Delegate Live Demo

31 31 .NET defines a convention (pattern) for defining events:  http://msdn.microsoft.com/en-us/library/aa645739(v=vs.71).aspx http://msdn.microsoft.com/en-us/library/aa645739(v=vs.71).aspx  Delegates which are used for events:  Have names formed by a verb + EventHandler  Accept two parameters:  Event sender – System.Object  Event information – inherited from System.EventArgs  No return value ( void ) Custom Events: ConventionCustom Events: Convention

32 32  Example:  Events:  Are declared public  Begin with a capital letter  End with a verb Custom Events: Convention (2)Custom Events: Convention (2) public delegate void ItemChangedEventHandler( object sender, ItemChangedEventArgs eventArgs); object sender, ItemChangedEventArgs eventArgs); public event ItemChangedEventHandler ItemChanged;

33 33  To fire an event a special protected void method is created  Named after a specific action, e.g. OnVerb()  The receiver method (handler) is named in the form OnObjectEvent : Custom Events: Convention (3)Custom Events: Convention (3) protected void OnItemChanged() { …} private void OnOrderListItemChanged() { …}

34 Defining and Using EventsDefining and Using Events Live Demo

35 35  Delegates are data types that hold methods as their value  Generic delegates in C#  Action, Func and Predicate  Action, Func and Predicate  Anonymous methods simplify coding  Events allow subscribing for notifications about something happening in an object  Implement the "publish-subscribe" model Summary

36 ? ? ? ? ? ? ? ? ? https://softuni.bg/trainings/coursesinstances/details/8 OOP – Delegates and Events

37 License  This course (slides, examples, demos, videos, homework, etc.) is licensed under the "Creative Commons Attribution- NonCommercial-ShareAlike 4.0 International" licenseCreative Commons Attribution- NonCommercial-ShareAlike 4.0 International 37  Attribution: this work may contain portions from  "Fundamentals of Computer Programming with C#" book by Svetlin Nakov & Co. under CC-BY-SA licenseFundamentals of Computer Programming with C#CC-BY-SA  "OOP" course by Telerik Academy under CC-BY-NC-SA licenseOOPCC-BY-NC-SA

38 SoftUni Diamond Partners

39 Free Trainings @ Software University  Software University Foundation – softuni.orgsoftuni.org  Software University – High-Quality Education, Profession and Job for Software Developers  softuni.bg softuni.bg  Software University @ Facebook  facebook.com/SoftwareUniversity facebook.com/SoftwareUniversity  Software University @ YouTube  youtube.com/SoftwareUniversity youtube.com/SoftwareUniversity  Software University Forums – forum.softuni.bgforum.softuni.bg


Download ppt "Delegates and Events Callback Functionality and Event-Driven Programming Svetlin Nakov Technical Trainer Software University"

Similar presentations


Ads by Google