Advanced .NET Programming I 4th Lecture

Slides:



Advertisements
Similar presentations
Semantic Analysis and Symbol Tables
Advertisements

CHARLES UNIVERSITY IN PRAGUE faculty of mathematics and physics C# Language &.NET Platform 12 th -13 th Lecture Pavel Ježek.
Copyright © 2012 Pearson Education, Inc. Chapter 9 Delegates and Events.
Delegates and lambda functions Jim Warren, COMPSCI 280 S Enterprise Software Development.
CHARLES UNIVERSITY IN PRAGUE faculty of mathematics and physics C# Language &.NET Platform 2 nd Lecture Pavel Ježek
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
Cs164 Prof. Bodik, Fall Symbol Tables and Static Checks Lecture 14.
COMP More About Classes Yi Hong May 22, 2015.
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.
By Nicholas Policelli An Introduction to Java. Basic Program Structure public class ClassName { public static void main(String[] args) { program statements.
Putting it all together: LINQ as an Example. The Problem: SQL in Code Programs often connect to database servers. Database servers only “speak” SQL. Programs.
CHARLES UNIVERSITY IN PRAGUE faculty of mathematics and physics C# Language &.NET Platform 11 th Lecture Pavel Ježek
Lambda Expressions Version 1.0
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#
CHARLES UNIVERSITY IN PRAGUE faculty of mathematics and physics C# Language &.NET Platform 11 th Lecture Pavel Ježek
Satisfy Your Technical Curiosity C# 3.0 Raj Pai Group Program Manager Microsoft Corporation
BİL527 – Bilgisayar Programlama I Functions 1. Contents Functions Delegates 2.
CHARLES UNIVERSITY IN PRAGUE faculty of mathematics and physics C# Language &.NET Platform 2 nd Lecture Pavel Ježek
Copyright © 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 5-1 Why Write Methods? Methods are commonly used to break a problem down.
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
CHARLES UNIVERSITY IN PRAGUE faculty of mathematics and physics C# Language &.NET Platform 7 th Lecture Pavel Ježek
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
Advanced .NET Programming I 3nd Lecture
Advanced .NET Programming II 6th Lecture
Advanced .NET Programming II 4th Lecture
Lambda Expressions By Val Feldsher.
Upgrading Your C# Programming Skills to Be a More Effective Developer
Advanced .NET Programming I 8th Lecture
Advanced .NET Programming I 7th Lecture
Advanced .NET Programming I 6th Lecture
Functional Programming with Java
C# Event Processing Model
Pass by Reference, const, readonly, struct
Lecture 15 (Notes by P. N. Hilfinger and R. Bodik)
Dynamic Scoping Lazy Evaluation
Review for Final Exam.
CSE 341 Lecture 11 b closures; scoping rules
Advanced .NET Programming I 13th Lecture
Advanced .NET Programming I 9th Lecture
Advanced .NET Programming I 8th Lecture
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
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 4th Lecture
C# Language & .NET Platform 8th Lecture
C# Language & .NET Platform 12th Lecture
Chengyu Sun California State University, Los Angeles
Presentation transcript:

Advanced .NET Programming I 4th 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)

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); }); list.ForAll(delegate (Node p) { sum += p.value; }); } formal parameter code method code is specified in-place does not require the declaration of a named method anonymous method can access Foo's local variable sum 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 anonymous methods must not access ref or out parameters of the enclosing method

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

Outer Variables If anonymous methods access variables of the enclosing method these variables are evacuated into a dummy object (capturing) – all anonymous methods and the enclosing method itself are then using a single “evacuated” variable (see next slide). delegate int Adder(); class Test { static Adder CreateAdder() { int x = 0; return delegate { x++; return x; }; } static void Main() { Adder add = CreateAdder(); Console.WriteLine(add()); x++; return x; dummy object delegate (closure) add 3 1 2 The dummy object lives as long as the delegate object Output: 1 2 3 Anonymous methods in C# always exist only as closures, never as “lambda functions” with free variables (open bindings)!

Example Output: --- Main: (m = Foo())(); Foo: x = 1 delegate: x = 2 second delegate: x = 13 delegate: x = 14 Foo: x = 14 second delegate: x = 24 second delegate: x = 34 --- Main: Foo()(); second delegate: x = 44 delegate void MyDelegate(); class Program { static MyDelegate Foo() int x = 1; Console.WriteLine("Foo: x = {0}", x); MyDelegate d = delegate { x++; Console.WriteLine("delegate: x = {0}", x); }; d(); MyDelegate d2 = delegate { x += 10; Console.WriteLine("second delegate: x = {0}", x); }; d2(); return d2; } static void Main(string[] args) MyDelegate m; Console.WriteLine(“--- Main: (m = Foo())();"); (m = Foo())(); m(); Console.WriteLine(“--- Main: Foo()();"); Foo()();

Lambda Expressions (2b) 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 Lambda expressions in C# always exist only as closures, and never as “lambda functions” with free variables (open bindings)! Pavel Ježek C# 3.0 and .NET 3.5