Delegates Programming in C# Delegates CSE 494R (proposed course for 459 Programming in C#) Prof. Roger Crawfis.

Slides:



Advertisements
Similar presentations
Optional Static Typing Guido van Rossum (with Paul Prescod, Greg Stein, and the types-SIG)
Advertisements

Generics Programming in C# Generics CSE 494R (proposed course for 459 Programming in C#) Prof. Roger Crawfis.
Generics, Lists, Interfaces
Object Oriented Programming with Java
CHARLES UNIVERSITY IN PRAGUE faculty of mathematics and physics C# Language &.NET Platform 14 th Lecture Pavel Ježek
Equality Programming in C# Equality CSE 494R (proposed course for 459 Programming in C#) Prof. Roger Crawfis.
1 Pointers, Dynamic Data, and Reference Types Review on Pointers Reference Variables Dynamic Memory Allocation –The new operator –The delete operator –Dynamic.
Shallow Versus Deep Copy and Pointers Shallow copy: when two or more pointers of the same types point to the same memory – They point to the same data.
Types in programming languages What are types, and why do we need them? Types in programming languages1.
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.
CSE 332: C++ Overloading Overview of C++ Overloading Overloading occurs when the same operator or function name is used with different signatures Both.
11 Values and References Chapter Objectives You will be able to: Describe and compare value types and reference types. Write programs that use variables.
C++ Programming: Program Design Including Data Structures, Fourth Edition Chapter 13: Pointers, Classes, Virtual Functions, and Abstract Classes.
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.
Extension Methods Programming in C# Extension Methods CSE Prof. Roger Crawfis.
REFACTORING Lecture 4. Definition Refactoring is a process of changing the internal structure of the program, not affecting its external behavior and.
Data Structures Using C++ 2E Chapter 3 Pointers and Array-Based Lists.
C++ Programming: From Problem Analysis to Program Design, Fourth Edition Chapter 14: Pointers, Classes, Virtual Functions, and Abstract Classes.
“is a”  Define a new class DerivedClass which extends BaseClass class BaseClass { // class contents } class DerivedClass : BaseClass { // class.
CSE 332: C++ templates This Week C++ Templates –Another form of polymorphism (interface based) –Let you plug different types into reusable code Assigned.
Object Composition Interfaces Collections Covariance Object class Programming using C# LECTURE 10.
Polymorphism, Inheritance Pt. 1 COMP 401, Fall 2014 Lecture 7 9/9/2014.
1 COSC3557: Object-Oriented Programming Haibin Zhu, Ph. D. Associate Professor of CS, Nipissing University.
Introduction to Building Windows 8.1 & Windows Phone Applications.
Session 08 Module 14: Generics and Iterator Module 15: Anonymous & partial class & Nullable type.
Chapter 10 Inheritance and Polymorphism
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)
C/C++ 3 Yeting Ge. Static variables Static variables is stored in the static storage. Static variable will be initialized once. 29.cpp 21.cpp.
Object Oriented Programming Elhanan Borenstein Lecture #10 copyrights © Elhanan Borenstein.
Types in programming languages1 What are types, and why do we need them?
C# part II Delegates and Events Delegates and Events Dynamic functions Dynamic functions Extension methods Extension methods Closures Closures.
Module 8: Delegates and Events. Overview Delegates Multicast Delegates Events When to Use Delegates, Events, and Interfaces.
 In the java programming language, a keyword is one of 50 reserved words which have a predefined meaning in the language; because of this,
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.
Events Programming in C# Events CSE 494R (proposed course for 459 Programming in C#) Prof. Roger Crawfis.
Introduction to C# By: Abir Ghattas Michel Barakat.
Overview of C++ Polymorphism
Object Oriented Programming and Data Abstraction Rowan University Earl Huff.
Chapter 1 C++ Basics Review (Section 1.4). Classes Defines the organization of a data user-defined type. Members can be  Data  Functions/Methods Information.
Java & C++ Comparisons How important are classes and objects?? What mechanisms exist for input and output?? Are references and pointers the same thing??
Methods main concepts – method call – object 's methods – actual parameters – method declaration – formal parameters – return value other concepts – method.
Arrays and Indexers Programming in C# Arrays and Indexers CSE 494R (proposed course for 459 Programming in C#) Prof. Roger Crawfis.
1.NETDelegates & eventsNOEA / PQC 2007 Delegates & events Observer pattern Delegates –Semantics –Cil – kode –Anvendelse Events.
1.NETDelegates & eventsNOEA / PQC 2007 Delegates & events Observer pattern Delegates –Semantics –Cil – code –Usage Events Asynchronious delegates.
CSE 332: C++ Overloading Overview of C++ Overloading Overloading occurs when the same operator or function name is used with different signatures Both.
1 New Features in C# 2.0 Generic Types Iterators Simplified Delegates Anonymous Methods Partial Types Various © University of Linz, Institute for System.
INTRODUCTION TO CLASSES & OBJECTS CREATING CLASSES USING C#
Object-Oriented Programming Review 1. Object-Oriented Programming Object-Oriented Programming languages vary but generally all support the following features:
Inheritance Modern object-oriented (OO) programming languages provide 3 capabilities: encapsulation inheritance polymorphism which can improve the design,
C# for C++ Programmers 1.
Creating and Using Objects, Exceptions, Strings
Advanced .NET Programming I 3nd Lecture
Delegates and Events 14: Delegates and Events
Methods Attributes Method Modifiers ‘static’
6 Delegate and Lambda Expressions
Programming in C# Comparison (Sorting)
Java Programming Language
Pointers, Dynamic Data, and Reference Types
Delegates & Events 1.
CIS 199 Final Review.
Advanced .NET Programming I 3rd Lecture
Advanced .NET Programming I 4th Lecture
Corresponds with Chapter 5
C++ Object Oriented 1.
Static Binding Static binding chooses the function in the class of the base class pointer, ignoring any versions in the class of the object actually.
Chengyu Sun California State University, Los Angeles
Introduction to Methods and Interfaces
Presentation transcript:

Delegates Programming in C# Delegates CSE 494R (proposed course for 459 Programming in C#) Prof. Roger Crawfis

Delegates Delegates are type definitions for function pointers. Once defined, they allow for type-safe (static) variables (instances) which point to functions (methods). They specify the signature of an individual method. public delegate Complex Func1D(Complex x); Return Type Parameters: order and type Type Definition Name This name does not matter.

Delegates vs. Interfaces Delegates are similar to interfaces: they specify a contract between a caller and an implementer. Interface: specifying an entire interface Delegate: specifying a single function Interface: created at compile-time Delegate: created at run-time. Can be used to dynamically hook up callbacks between objects that weren’t originally designed to work together.

Examples The following are type definitions: public delegate double Function( double x ); public delegate bool Predicate( double x ); public delegate void Action( double x ); We can now assign variables these types: private Function log10 = System.Math.Log10; private Predicate isNegative = null; private Function operation = null; private Action print = new Action(Console.Writeline); Reference types – default value of null.

Examples Now we can use these variables. Call them just like you would a method: double y = log10(100.0); y += operation(-2); if( isNegative (y) ) … (new Action(Console.Writeline))(y);

Assigning Values Any matching method can be assigned to a delegate instance delegate void Notifier (string sender); void SayHello( string name) { Console.WriteLine( “Hello from " + name); } greetings = new Notifier(SayHello); greetings(”Roger”); // SayGoodBye(“Roger") => “Hello from Roger“ Note If null, a delegate variable must not be called (otherwise it results in an exception). Delegate variables are first class objects. They can be stored in a data structure, passed as a parameter, etc.

Creating a Delegate Value new DelegateType (instance.Method) A delegate variable stores a method and its target. It does not store any parameters. new Notifier( myGreeting.SayHello ); The target, instance, can be this (and can be omitted) new Notifier( SayHello ); The method can be static. In this case the class name must be specified instead of the instance variable name. new Notifier( MyClass.StaticSayHello ); The method can not be abstract (impossible), but it can be virtual.

Method Signatures The method signature must match the signature of DelegateType same number of parameters same parameter types (including the return type) same parameter attributes (ref, out) With.NET 2.0 delegates are contra-variant in the parameters (any base type of the specified type) and covariant in the return type (any type derived from the specified return type).

Multicast Delegates 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. Notifier greetings; greetings = new Notifier(SayHello); greetings += new Notifier(SayGoodBye); greetings("John");// "Hello from John" // "Good bye from John" greetings -= new Notifier(SayHello); greetings("John");// "Good bye from John“ If the multicast delegate is a function, the value of the last call is returned. Avoid this! If the multicast delegate has an out parameter, the parameter of the last call is returned. ref Parameters are passed through all methods. Do not assume any order to the calls.

Assignment of Delegates delegate void Printer(string s); void Foo(string s) { Console.WriteLine(s); } Printer print; print = new Printer(this.Foo); print = this.Foo; print = Foo; simplified forms: delegate type is inferred from the type of the left-hand side delegate double Function(double x); double Foo(double x) { return x * x; } Printer print = Foo; Function square = Foo; assigns Foo(string s) assigns Foo(double x) overloading is resolved using the type of the left-hand side

Generic Delegates delegate bool Check (T value); class Payment { public DateTime date; public int amount; } internal class Account { private IList payments = new List (); public void Add(Payment p) { payments.Add(p); } public int AmountPayed( Check matches ) { int val = 0; foreach (Payment p in payments) if ( matches(p) ) val += p.amount; return val; } bool PaymentsAfter( Payment p ) { return DateTime.Compare( p.date, myDate ) >= 0; }... myDate = new DateTime(2001, 11, 9); int val = account.AmountPayed( new Check (PaymentsAfter) ); A check method is passed, which checks for every Payment, whether it is eligible

Delegates Programming in C# Delegates CSE 494R (proposed course for 459 Programming in C#) Prof. Roger Crawfis