Delegates and Events Svetlin Nakov Telerik Corporation www.telerik.com.

Slides:



Advertisements
Similar presentations
Extension Methods, Anonymous Types LINQ Query Keywords, Lambda Expressions Svetlin Nakov Telerik Corporation
Advertisements

Copyright © 2012 Pearson Education, Inc. Chapter 9 Delegates and Events.
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++
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.
2.3 Cool features in C# academy.zariba.com 1. Lecture Content 1.Extension Methods 2.Anonymous Types 3.Delegates 4.Action and Func 5.Events 6.Lambda Expressions.
Java CourseWinter 2009/10. Introduction Object oriented, imperative programming language. Developed: Inspired by C++ programming language.
C# Event Processing Model Solving The Mystery. Agenda Introduction C# Event Processing Macro View Required Components Role of Each Component How To Create.
Inheritance. Types of Inheritance Implementation inheritance means that a type derives from a base type, taking all the base type’s member fields and.
Understanding Events and Exceptions Lesson 3. Objective Domain Matrix Skills/ConceptsMTA Exam Objectives Understand events and event handling Understand.
Delegates and lambda functions Jim Warren, COMPSCI 280 S Enterprise Software Development.
Specialization and Inheritance Chapter 8. 8 Specialization Specialized classes inherit the properties and methods of the parent or base class. A dog is.
Extension Methods, Anonymous Types LINQ Query Keywords, Lambda Expressions Based on material from Telerik Corporation.
CIS 3301 C# Lesson 13 Interfaces. CIS 3302 Objectives Understand the Purpose of Interfaces. Define an Interface. Use an Interface. Implement Interface.
Lecture Set 11 Creating and Using Classes Part B – Class Features – Constructors, Methods, Fields, Properties, Shared Data.
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.
Delegates and Events Callback Functionality and Event-Driven Programming Svetlin Nakov Technical Trainer Software University
An Object-Oriented Approach to Programming Logic and Design Chapter 3 Using Methods and Parameters.
Chapter 14 Abstract Classes and Interfaces. Abstract Classes An abstract class extracts common features and functionality of a family of objects An abstract.
Module 8: Delegates and Events. Overview Delegates Multicast Delegates Events When to Use Delegates, Events, and Interfaces.
Callback Functionality and Event-Driven Programming
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.
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All rights reserved. 1 Chapter 15 Event-Driven Programming and.
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.
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All rights reserved. 1 Chapter 15 Event-Driven Programming and.
V 1.0 OE-NIK HP 1 Advanced Programming Delegates, Events.
Arrays & Enum & Events. Arrays Arrays are data structures consisting of related data items of the same type. Arrays are fixed-length entities—they remain.
 ASP.NET provides an event based programming model that simplifies web programming  All GUI applications are incomplete without enabling actions  These.
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 –
CIS NET Applications1 Chapter 6 – Events. CIS NET Applications2 Objectives Delegate-based Events.NET event support Practical guides for managing.
Module 5: Programming with C#. Overview Using Arrays Using Collections Using Interfaces Using Exception Handling Using Delegates and Events.
Building Web Applications with Microsoft ASP
C# for C++ Programmers 1.
Creating and Using Objects, Exceptions, Strings
Chapter 15 Event-Driven Programming and Animations
Classes (Part 1) Lecture 3
INF230 Basics in C# Programming
Computing with C# and the .NET Framework
2.7 Inheritance Types of inheritance
Delegates and Events 14: Delegates and Events
Chapter Eleven Handling Events.
Chapter 5: Programming with C#
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.
Generics, Lambdas, Reflections
C# Event Processing Model
AVG 24th 2015 ADVANCED c# - part 1.
6 Delegate and Lambda Expressions
Delegates & Events 1.
Object Oriented Practices
Object Oriented Practices
Lesson 7. Events, Delegates, Generics.
Tonga Institute of Higher Education
Programming in C# CHAPTER - 8
Generics, Lambdas, Reflections
CIS 199 Final Review.
Class.
Advanced .NET Programming I 4th Lecture
Creating and Using Classes
Chengyu Sun California State University, Los Angeles
Events, Delegates, and Lambdas
CS 240 – Advanced Programming Concepts
Chengyu Sun California State University, Los Angeles
Presentation transcript:

Delegates and Events Svetlin Nakov Telerik Corporation www.telerik.com

Table of Contents What are Delegates? Singlecast and Multicast Delegates Generic Delegates and Anonymous Methods Predicates Events Events vs. Delegates When to Use Interfaces, Events and Delegates

Delegates in .NET Framework

What are Delegates? Delegates are types that hold a method reference Describe the signature of given method Number and types of the parameters The return type Their "values" are methods These methods match their signature (parameters and return types) Delegates are reference types

What are Delegates? (2) Delegates are roughly similar to function pointers in C and C++ Contain a strongly-typed pointer (reference) to a method They can point to both static and instance methods Used to perform callbacks invocations Used to implement the "publish-subscribe" model

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

Simple Delegate Live Demo

Singlecast and Multicast Delegates

Types of Delegates Singlecast delegates Multicast delegates Reference to one method only Multicast delegates Linked list of references to methods In C# only multicast delegates are used Declared using the delegate keyword

Multicast Delegates When calling a multicast delegate, all the methods of its list are invoked Delegate may return a value The result of the execution is the result of the last method invoked Delegates may contain ref or out parameter An exception can be thrown by any of the methods of a multicast delegate The methods after this one are not invoked

Multicast Delegates (2) When talking about a delegate usually we mean multicast delegate They inherit System.MulticastDelegate ... ... which inherits a System.Delegate

Properties and Methods Combine() / += – concatenates the invocation lists of an array of delegates with equal signatures Remove() / -= – removes a method from the invocation list GetInvocationList() – returns an array of delegates – one for each of the methods in the invocation list Method – returns the methods' descriptions in the delegate

Multicast Delegates – Example public delegate void StringDelegate(string value); public class TestDelegateClass { void PrintString(string value) Console.WriteLine(value); } void PrintStringLength(string value) Console.WriteLine("Length = {0}", value.Length); static void PrintInvocationList(Delegate someDelegate) Delegate[] list = someDelegate.GetInvocationList(); foreach (Delegate d in list) Console.Write(" {0}", d.Method.Name);

Multicast Delegates – Example (2) public static void Main() { TestDelegateClass tdc = new TestDelegateClass(); StringDelegate printDelegate = new StringDelegate(tdc.PrintString); PrintInvocationList(printDelegate); // Prints: ( PrintString ) // Invoke the delegate combinedDelegate("test"); }

Multicast Delegates Live Demo

Generic Delegates

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

Definition and Parameters Anonymous Methods Definition and Parameters

Anonymous Methods We are sometimes forced to create a class or a method just for the sake of using a delegate The code involved is often relatively short and simple Anonymous methods lets you define an nameless method called by a delegate Lambda functions are variant of anonymous methods with shorter syntax

The Standard Way class SomeClass { delegate void SomeDelegate(); public void InvokeMethod() SomeDelegate d = new SomeDelegate(SomeMethod); d(); } void SomeMethod() MessageBox.Show("Hello");

Using Anonymous Methods The same can be accomplished by using an anonymous method: class SomeClass { delegate void SomeDelegate(); public void InvokeMethod() SomeDelegate d = delegate() MessageBox.Show("Hello"); }; d(); }

Using Lambda Function The same can be accomplished by using a lambda function: class SomeClass { delegate void SomeDelegate(); public void InvokeMethod() SomeDelegate d = (() => MessageBox.Show("Hello"); }); d(); }

Anonymous Methods with Parameters Define the parameters in the parenthesis The method signature must match the definition of the delegate class SomeClass { delegate void SomeDelegate(string str); public void InvokeMethod() SomeDelegate d = delegate(string str) MessageBox.Show(str); }; d("Hello"); }

Anonymous Methods with Parameters (2) You can omit the empty parenthesis after the delegate keyword class SomeClass { delegate void SomeDelegate(string str); public void InvokeMethod() SomeDelegate d = delegate MessageBox.Show("Hello"); }; d("this parameter is ignored"); }

Using Anonymous Methods with Parameters Live Demo

Predicates

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

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

Predicates Live Demo

Events

Events In component-oriented programming components send events to their owner Events are notifications of something For example moving the mouse causes event The object which causes an event is called event sender The object which receives an event is called event receiver To be able to receive an event the event receivers should first "subscribe for the event"

Events in .NET 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 events public event SomeDelegate eventName;

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

Events vs. Delegates Events are not the same as member fields of type delegate Events can be members of an interface unlike delegates Calling of an event can only be done in the class where it is defined By default the access to the events is synchronized (thread-safe) ≠ public MyDelegate m; public event MyDelegate m;

Events – Convention .NET defines a convention for naming the events and a standard parameters Delegates which are used for events: Have names formed by a verb + EventHandler Accept two parameters: Event sender – System.Object Inheritor of System.EventArgs type, which contains information about the event No return value (return void)

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

Events – Convention (3) To fire an event a special protected void method is created Having name like OnVerb() The receiver method (handler) is named in in the form OnObjectEvent : protected void OnItemChanged() { … } private void OnOrderListItemChanged() { … }

Defining and Using Events Live Demo

The Delegate System.EventHandler

The Delegate System.EventHandler 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 base class with no information for the event public delegate void EventHandler( Object sender, EventArgs e);

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

The Delegate System.EventHandler Live Demo

The Delegate System.EventHandler<T> If an event brings additional data the generic EventHandler<T> delegate is used TEventArgs is a custom type derived from EventArgs and holds the event data Example: Mouse click event hold information about the mouse position, which button is clicked, etc. public delegate void EventHandler<TEventArgs>( Object sender, TEventArgs e) where TEventArgs : EventArgs

Events as Members in Interface Events can be interface members: When implementing an event from interface a specific add / remove methods can be defined: public interface IClickable { event ClickEventHandler Click; } public event ClickEventHandler Click { add { … } remove { … } }

Events as Interface Members Live Demo

Interfaces vs. Events vs. Delegates In .NET we can implement "callback" by using interfaces, delegates or events When to use interfaces? If a class exposes lots of callback methods as a group When to use events? When we develop components which have to notify their owner about something When we need compatibility with the .NET component model

Interfaces vs. Events vs. Delegates (2) When to use delegates? When we have a single callback method which is not confined to the .NET component model

Delegates and Events ? ? ? ? ? Questions? ? ? ? ? ? ?

Exercises Explain what are the delegates and events in .NET. By using delegates develop an universal static method to calculate the sum of infinite convergent series with given precision depending on a function of its term. By using proper functions for the term calculate with a 2-digit precision the sum of the infinite series: 1 + 1/2 + 1/4 + 1/8 + 1/16 + … 1 + 1/2! + 1/3! + 1/4! + 1/5! + … 1 + 1/2 - 1/4 + 1/8 - 1/16 + …

Exercises (2) What does the approved convention for events in .NET recommend? Define a class Person, which describes a person and has the following properties: first name, last name, gender, birth date. Add an event of the system delegate System.EventHandler to the Person class per each of its properties, that fires when the value of the property changes.

Exercises (2) Create a class PropertyChangedEventArgs, inheritor of the System.EventArgs class and define 3 properties – name of the property changed (string), old value (object) and new value (object) together with a proper constructor. Create a delegate PropertyChangedEventHandler to handle property change events, that accepts 2 parameters – a sender object and a PropertyChangedEventArgs.

Exercises (3) Write another version of the Person class, which has just one event named PropertyChanged of type PropertyChangedEventHandler, which activates when any of the properties of the class changes (called with proper parameters respectively). Extract the definition of the PropertyChanged event in a separate interface IPropertyChangeNotification and change the class in such a way that it implements the interface.