Advanced .NET Programming I 3nd Lecture

Slides:



Advertisements
Similar presentations
CHARLES UNIVERSITY IN PRAGUE faculty of mathematics and physics C# Language &.NET Platform 12 th -13 th Lecture Pavel Ježek.
Advertisements

Copyright © 2012 Pearson Education, Inc. Chapter 9 Delegates and Events.
CHARLES UNIVERSITY IN PRAGUE faculty of mathematics and physics C# Language &.NET Platform 4 th Lecture Pavel Ježek
CHARLES UNIVERSITY IN PRAGUE faculty of mathematics and physics C# Language &.NET Platform 14 th Lecture Pavel Ježek
CHARLES UNIVERSITY IN PRAGUE faculty of mathematics and physics C# Language &.NET Platform 7 th & 8 th Lecture Pavel Ježek.
Extension Methods Programming in C# Extension Methods CSE Prof. Roger Crawfis.
Advanced .NET Programming I 13th Lecture
CHARLES UNIVERSITY IN PRAGUE faculty of mathematics and physics Advanced.NET Programming I 11 th Lecture Pavel Ježek
Delegates and lambda functions Jim Warren, COMPSCI 280 S Enterprise Software Development.
Introduction to C# C# is - elegant, type-safe, object oriented language enabling to build applications that run on the.NET framework - types of applications.
CHARLES UNIVERSITY IN PRAGUE faculty of mathematics and physics C# Language &.NET Platform 11 th Lecture Pavel Ježek
Delegates Programming in C# Delegates CSE 494R (proposed course for 459 Programming in C#) Prof. Roger Crawfis.
Session 08 Module 14: Generics and Iterator Module 15: Anonymous & partial class & Nullable type.
Lambda Expressions Version 1.0
Module 8: Delegates and Events. Overview Delegates Multicast Delegates Events When to Use Delegates, Events, and Interfaces.
CHARLES UNIVERSITY IN PRAGUE faculty of mathematics and physics Advanced.NET Programming I 10 th Lecture Pavel Ježek
Introduction to C# 2.0 An Advanced Look Adam Calderon Principal Engineer - Interknowlogy Microsoft MVP – C#
PROGRAMMING IN C#. Collection Classes (C# Programming Guide) The.NET Framework provides specialized classes for data storage and retrieval. These classes.
CHARLES UNIVERSITY IN PRAGUE faculty of mathematics and physics C# Language &.NET Platform 6 th Lecture Pavel Ježek
CHARLES UNIVERSITY IN PRAGUE faculty of mathematics and physics C# Language &.NET Platform 8 th Lecture Pavel Ježek
CHARLES UNIVERSITY IN PRAGUE faculty of mathematics and physics C# Language &.NET Platform 11 th Lecture Pavel Ježek
Introduction to Object-Oriented Programming Lesson 2.
CHARLES UNIVERSITY IN PRAGUE faculty of mathematics and physics C# Language &.NET Platform 9 th Lecture Pavel Ježek
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.
IAP C# 2011 Lecture 2: Delegates, Lambdas, LINQ Geza Kovacs.
CHARLES UNIVERSITY IN PRAGUE faculty of mathematics and physics C# Language &.NET Platform 4 th Lecture Pavel Ježek
- This slide is intentionally left blank - Some of the slides are based on University of Linz.NET presentations. © University of Linz, Institute for System.
CHARLES UNIVERSITY IN PRAGUE faculty of mathematics and physics C# Language &.NET Platform 7 th Lecture Pavel Ježek
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 –
1 Statements © University of Linz, Institute for System Software, 2004 published under the Microsoft Curriculum License.
1 New Features in C# 2.0 Generic Types Iterators Simplified Delegates Anonymous Methods Partial Types Various © University of Linz, Institute for System.
CHARLES UNIVERSITY IN PRAGUE faculty of mathematics and physics Advanced.NET Programming II 3 rd Lecture Pavel Ježek
CHARLES UNIVERSITY IN PRAGUE faculty of mathematics and physics Advanced.NET Programming II 2 nd Lecture Pavel Ježek
CHARLES UNIVERSITY IN PRAGUE faculty of mathematics and physics Advanced.NET Programming I 2 nd Lecture Pavel Ježek
C# for C++ Programmers 1.
Advanced .NET Programming I 2nd Lecture
Lambda Expressions Version 1.1
Delegates and Events Svetlin Nakov Telerik Corporation
Advanced .NET Programming II 4th Lecture
Lambda Expressions By Val Feldsher.
Methods Attributes Method Modifiers ‘static’
Upgrading Your C# Programming Skills to Be a More Effective Developer
Advanced .NET Programming I 8th Lecture
Advanced .NET Programming I 4th Lecture
Chapter 5: Programming with C#
Advanced .NET Programming I 6th Lecture
.NET and .NET Core: Languages, Cloud, Mobile and AI
Functional Programming with Java
.NET and .NET Core 5.2 Type Operations Pan Wuming 2016.
C# Event Processing Model
6 Delegate and Lambda Expressions
Pointers, Dynamic Data, and Reference Types
Delegates & Events 1.
Pointers, Dynamic Data, and Reference Types
Advanced .NET Programming I 5th Lecture
Standard Version of Starting Out with C++, 4th Edition
C# Language & .NET Platform 10th Lecture
Advanced .NET Programming I 7th Lecture
- This slide is intentionally left blank -
Advanced .NET Programming I 3rd Lecture
Advanced .NET Programming I 4th Lecture
C# Language & .NET Platform 11th Lecture
Advanced .NET Programming I 6th Lecture
Corresponds with Chapter 5
C# Language & .NET Platform 3rd Lecture
C# Language & .NET Platform 9th Lecture
C# Language & .NET Platform 12th Lecture
Chengyu Sun California State University, Los Angeles
Events, Delegates, and Lambdas
Presentation transcript:

Advanced .NET Programming I 3nd Lecture Pavel Ježek pavel.jezek@d3s.mff.cuni.cz Some of the slides are based on University of Linz .NET presentations. © University of Linz, Institute for System Software, 2004 published under the Microsoft Curriculum License (http://www.msdnaa.net/curriculum/license_curriculum.aspx)

Type Variance

Sorting: IComparable and IComparer IComparable is interface for types with order classes implementing IComparable are values types like Int32, Double, DateTime, … class Enum as base class of all enumeration types class String IComparer is interface for the realization of compare operators public interface IComparable { int CompareTo(object obj); // <0 if this < obj, 0 if this == obj, >0 if this > obj } public interface IComparable<in T> { int CompareTo(T obj); // <0 if this < obj, 0 if this == obj, >0 if this > obj public interface IComparer { int Compare(object x, object y); // <0 if x < y, 0 if x == y, >0 if x > y } public interface IComparer<in T> { int Compare(T x, T y); // <0 if x < y, 0 if x == y, >0 if x > y

IEnumerable and IEnumerator (1) Anything which is enumerable is represented by interface IEnumerable IEnumerator realizes an iterator Also generic versions IEnumerable<out T> and IEnumerator<out T> Enumerator should throw an InvalidOperationException on concurrent modification! interface IEnumerable { IEnumerator GetEnumerator(); } interface IEnumerator { object Current {get;} bool MoveNext(); void Reset(); }

CLI Type Inheritance pointers (C#: Type *) System.Object (C# keyword: object) interfaces (C# keyword: interface) System.String (C# keyword: string) System.Array System.Delegate arrays (C#: Type[] or Type[,]) System.MulticastDelegate System.ValueType delegates (C# keyword: delegate) user-defined classes (C# keyword: class) simple types System.Int32 (C# keyword: int) System.Double (C# keyword: double) System.Int64 (C# keyword: long) System.Enum System.Nullable (C#: Type?) user-defined structures (C# keyword: struct) System.Boolean (C# keyword: bool) enumerations (C# keyword: enum) …

Delegate = Method Type Declaration of a delegate type delegate void Notifier (string sender); // ordinary method signature // with the keyword delegate Declaration of a delegate variable Notifier greetings; Assigning a method to a delegate variable void SayHello(string sender) { Console.WriteLine("Hello from " + sender); } greetings = new Notifier(SayHello); Calling a delegate variable greetings("John"); // invokes SayHello("John") => "Hello from John"

Assigning Different Methods Every matching method can be assigned to a delegate variable void SayGoodBye(string sender) { Console.WriteLine("Good bye from " + sender); } greetings = new Notifier(SayGoodBye); greetings("John"); // SayGoodBye("John") => "Good bye from John" Note A delegate variable can have the value null (no method assigned). If null, a delegate variable must not be called (otherwise exception). Delegate variables are first class objects: can be stored in a data structure, passed as a parameter, etc.

Creating a Delegate Value new DelegateType (obj.Method) A delegate variable stores a method and its receiver, but no parameters ! new Notifier(myObj.SayHello); obj can be this (and can be omitted) new Notifier(SayHello); Method can be static. In this case the class name must be specified instead of obj. new Notifier(MyClass.StaticSayHello); Method signature must match the signature of DelegateType - same number of parameters - same parameter types (including the return type) - same parameter kinds (ref, out, value)

Simplified Creation 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 form: delegate type is infered 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

Multicast Delegates A delegate variable can hold multiple values at the same time 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" Note If the multicast delegate is a function, the value of the last call is returned If the multicast delegate has an out parameter, the parameter of the last call is returned. ref-Parameter are passed through all methods.

Delegates Are Immutable

Delegate Variance

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

Delegate Variance

Standard Delegates public delegate void Action() ... public delegate void Action<T1, T2, T3>(T1 arg1, T2 arg2, T3 arg3) public delegate TResult Func<TResult>() public delegate TResult Func<T1, T2, TResult>(T1 arg1, T2 arg2) public delegate bool Predicate<T>(T obj )

Ordinary Delegates class C { int sum = 0; void SumUp(Node p) { sum += p.value; } void Print(Node p) { Console.WriteLine(p.value); } void Foo() { List list = new List(); list.ForAll(SumUp); list.ForAll(Print); } requires the declaration of a named method (SumUp, Print, ...) SumUp and Print cannot access the local variables of Foo => sum must be declared as a global field delegate void Visitor(Node p); class List { Node[] data = ...; ... public void ForAll(Visitor visit) { for (int i = 0; i < data.Length; i++) visit(data[i]); }

Anonymous Methods formal parameter code class List { ... public void ForAll(Visitor visit) { } delegate void Visitor(Node p); class C { void Foo() { List list = new List(); int sum = 0; list.ForAll(delegate (Node p) { Console.WriteLine(p.value); }); } formal parameter code method code is specified in-place does not require the declaration of a named method return terminates the anonymous method (not the enclosing method) Restrictions anonymous methods must not have formal parameters of the kind params T[] anonymous methods must not be assigned to object

Further Simplification delegate void EventHandler (object sender, EventArgs arg); Button button = new Button(); Button.Click += delegate (object sender, EventArgs arg) { Console.WriteLine("clicked"); }; Can be simplified as follows Button.Click += delegate { Console.WriteLine("clicked"); }; Formal parameters can be omitted if they are not used in the method body Restriction Formal parameters can only be omitted if the delegate type does not have out parameters

Lambda Expressions Example of C# 2.0 anonymous method: class Program { delegate T BinaryOp<T>(T x, T y); static void Method<T>(BinaryOp<T> op, T p1, T p2) { Console.WriteLine(op(p1, p2)); } static void Main() { Method(delegate(int a, int b) { return a + b; }, 1, 2); C# 3.0 lambda expressions provide further simplification: Method((a, b) => a + b, 1, 2); Pavel Ježek C# 3.0 and .NET 3.5

Lambda Expressions (2) Expression or statement body Implicitly or explicitly typed parameters Examples: x => x + 1 // Implicitly typed, expression body x => { return x + 1; } // Implicitly typed, statement body (int x) => x + 1 // Explicitly typed, expression body (int x) => { return x + 1; } // Explicitly typed, statement body (x, y) => x * y // Multiple parameters () => Console.WriteLine() // No parameters A lambda expression is a value, that does not have a type but can be implicitly converted to a compatible delegate type delegate R Func<A,R>(A arg); Func<int,int> f1 = x => x + 1; // Ok Func<int,double> f2 = x => x + 1; // Ok Func<double,int> f3 = x => x + 1; // Error – double cannot be // implicitly converted to int Pavel Ježek C# 3.0 and .NET 3.5

Lambda Expressions (3) Lambda expressions participate in inference process of type arguments of generic methods In initial phase, nothing is inferred from arguments that are lambda expressions Following the initial phase, additional inferences are made from lambda expressions using an iterative process Pavel Ježek C# 3.0 and .NET 3.5

Lambda Expressions (4) Generic extension method example: public class List<T> : IEnumerable<T>, … { … } public static class Sequence { public static IEnumerable<S> Select<T,S>( this IEnumerable<T> source, Func<T, S> selector) { foreach (T element in source) yield return selector(element); } Calling extension method with lambda expression: List<Customer> customers = GetCustomerList(); IEnumerable<string> names = customers.Select(c => c.Name); Rewriting extension method call: IEnumerable<string> names = Sequence.Select<T, S>(customers, c => c.Name); T type argument is inferred to Customer based on source argument type Sequence.Select<Customer, S>(customers, c => c.Name) c lambda expression argument type is infered to Customer Sequence.Select<Customer, S>(customers, (Customer c) => c.Name) S type argument is inferred to string based on return value type of the lambda expression Sequence.Select<Customer, string>(customers, (Customer c) => c.Name) Pavel Ježek C# 3.0 and .NET 3.5