Advanced .NET Programming I 13th Lecture

Slides:



Advertisements
Similar presentations
The Microsoft Technical Roadshow 2007 Language Enhancements and LINQ Daniel Moth Developer & Platform Group Microsoft Ltd
Advertisements

CHARLES UNIVERSITY IN PRAGUE faculty of mathematics and physics C# Language &.NET Platform 12 th -13 th Lecture Pavel Ježek.
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 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
C# 3.0 Tom Roeder CS fa. Version 3 From PDC 2005 preview compiler available LINQ: language-integrated query High level points: adds native query.
C# Tutorial From C++ to C#. Some useful links Msdn C# us/library/kx37x362.aspxhttp://msdn.microsoft.com/en- us/library/kx37x362.aspx.
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.
1 Binary Files ผศ. ดร. หมัดอามีน หมันหลิน Faculty of IST, MUT
CHARLES UNIVERSITY IN PRAGUE faculty of mathematics and physics Advanced.NET Programming I 11 th Lecture Pavel Ježek
CHARLES UNIVERSITY IN PRAGUE faculty of mathematics and physics C# 3.0 and.NET 3.5: A Brief Overview Pavel Ježek.
HeuristicLab. Motivation  less memory pressure no DOM single pass linear process  less developer effort no interfaces to implement  modularity & flexibility.
Serialization  What is Serialization?  System.Serialization  Scenarios in Serialization  Basic Serialization  Custom Serialization.
CHARLES UNIVERSITY IN PRAGUE faculty of mathematics and physics C# Language &.NET Platform 11 th Lecture Pavel Ježek
Inheritance and Polymorphism Daniel Liang, Introduction to Java Programming.
Session 08 Module 14: Generics and Iterator Module 15: Anonymous & partial class & Nullable type.
Hoang Anh Viet Hà Nội University of Technology Chapter 1. Introduction to C# Programming.
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# 2.0 and Future Directions Anders Hejlsberg Technical Fellow Microsoft Corporation.
1 Interfaces and Abstract Classes Chapter Objectives You will be able to: Write Interface definitions and class definitions that implement them.
Lambda Expressions Version 1.0
C# part II Delegates and Events Delegates and Events Dynamic functions Dynamic functions Extension methods Extension methods Closures Closures.
Advanced C# Types Tom Roeder CS fa. From last time out parameters difference is that the callee is required to assign it before returning not the.
C#: Future Directions in Language Innovation Anders Hejlsberg TLN307 Technical Fellow Microsoft Corporation.
CHARLES UNIVERSITY IN PRAGUE faculty of mathematics and physics Advanced.NET Programming I 10 th Lecture Pavel Ježek
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
CHARLES UNIVERSITY IN PRAGUE faculty of mathematics and physics C# Language &.NET Platform 9 th Lecture Pavel Ježek
Satisfy Your Technical Curiosity C# 3.0 Raj Pai Group Program Manager Microsoft Corporation
CHARLES UNIVERSITY IN PRAGUE faculty of mathematics and physics C# Language &.NET Platform 2 nd Lecture Pavel Ježek
Introduction to C# By: Abir Ghattas Michel Barakat.
Wel come To Seminar On C#.
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
1 Statements © University of Linz, Institute for System Software, 2004 published under the Microsoft Curriculum License.
CHARLES UNIVERSITY IN PRAGUE faculty of mathematics and physics Advanced.NET Programming II 5 th Lecture Pavel Ježek
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 I 7 th 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
Advanced .NET Programming I 2nd Lecture
Advanced .NET Programming I 3nd Lecture
Advanced .NET Programming II 6th Lecture
Advanced .NET Programming I 8th Lecture
Advanced .NET Programming I 4th Lecture
Advanced .NET Programming I 7th Lecture
Microsoft .NET 3. Language Innovations Pan Wuming 2017.
Advanced .NET Programming I 6th Lecture
CS360 Windows Programming
.NET and .NET Core 5.2 Type Operations Pan Wuming 2016.
.NET and .NET Core 9. Towards Higher Order Pan Wuming 2017.
Advanced .NET Programming I 9th Lecture
Advanced .NET Programming I 8th Lecture
Advanced .NET Programming I 5th Lecture
C# Language & .NET Platform 10th Lecture
Advanced .NET Programming I 7th 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
Presentation transcript:

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

Lambda Expressions (připomenutí ze ZS) 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);

Lambda Expressions (2) (připomenutí ze ZS) 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 (3) (připomenutí ze ZS) 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

Lambda Expressions (4) (připomenutí ze ZS) 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)

Lambda Expressions as Delegates (připomenutí ze ZS – nový slide) When assigned to a delegate, equivalent code of an anonymous method is generated at compile time! value => (value + 2) * 10 Func<int, int> f = Compile time generation IL_0000: ldarg.0 IL_0001: ldc.i4.2 IL_0002: add IL_0003: ldc.i4.s 10 IL_0005: mul IL_0006: stloc.0 IL_0007: br.s IL_0009 IL_0009: ldloc.0 IL_000a: ret

Lambda Expressions as Expression Trees Permit lambda expressions to be represented as data structures instead of executable code Lambda expression convertible to delegate D (assignment causes code generation) is also convertible to expression tree (abstract syntax tree) of type System.Linq.Expressions.Expression<D> (assignment causes expression tree generation – compile time generation of code, that creates the expression tree [class instances] at runtime) Expression trees are immutable value => (value + 2) * 10 Func<int, int> f = Expression<Func<int, int>> e = Compile time generation Compile time generation IL_0000: ldarg.0 IL_0001: ldc.i4.2 IL_0002: add IL_0003: ldc.i4.s 10 IL_0005: mul IL_0006: stloc.0 IL_0007: br.s IL_0009 IL_0009: ldloc.0 IL_000a: ret new LambdaExpression( new BinaryExpression( ParameterExpression(“value”) ConstantExpression(2) ) ConstantExpression(10)

Expression Trees and LINQ

Expression Trees Classes inheriting from Expression (since .NET 3.5): System.Linq.Expressions.BinaryExpression System.Linq.Expressions.ConditionalExpression System.Linq.Expressions.ConstantExpression System.Linq.Expressions.InvocationExpression System.Linq.Expressions.LambdaExpression System.Linq.Expressions.MemberExpression System.Linq.Expressions.MethodCallExpression System.Linq.Expressions.NewExpression System.Linq.Expressions.NewArrayExpression System.Linq.Expressions.MemberInitExpression System.Linq.Expressions.ListInitExpression System.Linq.Expressions.ParameterExpression System.Linq.Expressions.TypeBinaryExpression System.Linq.Expressions.UnaryExpression New classes inheriting from Expression (since .NET 4.0): System.Linq.Expressions.BlockExpression System.Linq.Expressions.LoopExpression System.Linq.Expressions.TryExpression …

Lambda Expressions as Expression Trees value => (value + 2) * 10 Func<int, int> f = Expression<Func<int, int>> e = Compile time generation Compile time generation IL_0000: ldarg.0 IL_0001: ldc.i4.2 IL_0002: add IL_0003: ldc.i4.s 10 IL_0005: mul IL_0006: stloc.0 IL_0007: br.s IL_0009 IL_0009: ldloc.0 IL_000a: ret new LambdaExpression( new BinaryExpression( ParameterExpression(“value”) ConstantExpression(2) ) ConstantExpression(10) Runtime time generation by JIT machine code (e.g. x86) (code actually executed by real CPU)

Expression Trees to Dynamic Methods (via Implicit Reflection.Emit) Runtime generation of CIL code of a dynamic method from expression tree instance: value => (value + 2) * 10 Func<int, int> f = Expression<Func<int, int>> e = Compile time generation Compile time generation IL_0000: ldarg.0 IL_0001: ldc.i4.2 IL_0002: add IL_0003: ldc.i4.s 10 IL_0005: mul IL_0006: stloc.0 IL_0007: br.s IL_0009 IL_0009: ldloc.0 IL_000a: ret new LambdaExpression( new BinaryExpression( ParameterExpression(“value”) ConstantExpression(2) ) ConstantExpression(10) Runtime time generation f = e.Compile(); Runtime time generation by JIT machine code (e.g. x86) (code actually executed by real CPU)

Expression Trees – Hello world! Dynamically creating an expression tree for () => Console.WriteLine(“Hello world!”) lambda expression: delegate void VoidDelegate(); class Program { static void Main(string[] args) { MethodInfo mi = typeof(Console).GetMethod( "WriteLine", BindingFlags.Public | BindingFlags.Static, null, new Type[] { typeof(string) }, null ); Expression<VoidDelegate> expr = Expression.Lambda<VoidDelegate>( Expression.Call(mi, Expression.Constant("Hello world!") ) VoidDelegate d = expr.Compile(); d(); }

Expression Trees – Another Example delegate void Void1Delegate(int value); Console.Write("Enter a number: "); int number = int.Parse(Console.ReadLine()); MethodInfo mi = typeof(Console).GetMethod( "WriteLine", BindingFlags.Public | BindingFlags.Static, null, new Type[] { typeof(string), typeof(object) }, null ); ParameterExpression param = Expression.Parameter(typeof(int), "valueToAdd"); Expression<Void1Delegate> expr = Expression.Lambda<Void1Delegate>( Expression.Call( mi, Expression.Constant("Hello world! Value is {0}"), Expression.Convert( Expression.Add( param, Expression.Constant(number, typeof(int)) ), typeof(object) ) param Void1Delegate d = expr.Compile(); d(10); d(20);

Implementing Generic Complex, etc. struct IntWrapper { public int v; public IntWrapper(int value) { v = value; } public static IntWrapper operator +(IntWrapper a, IntWrapper b) { return new IntWrapper(a.v + b.v);

Implementing Generic Complex, etc. (a Problem) struct IntWrapper { public int v; public IntWrapper(int value) { v = value; } public static IntWrapper operator +(IntWrapper a, IntWrapper b) { return new IntWrapper(a.v + b.v); Cannot be rewritten to: struct Wrapper<T> { public T v; public Wrapper(T value) { public static Wrapper<T> operator +(Wrapper<T> a, Wrapper<T> b) { return new Wrapper<T>(a.v + b.v);

Implementing Generic Complex, etc. (using ExprTree) using System.Linq.Expressions; struct ValueWrapper<T> { public T v; private static Func<T, T, T> addProxy; static ValueWrapper() { // Creates (a, b) => a + b lambda expression at runtime ParameterExpression paramA = Expression.Parameter(typeof(T), "a"); ParameterExpression paramB = Expression.Parameter(typeof(T), "b"); BinaryExpression addExpr = Expression.Add(paramA, paramB); addProxy = Expression.Lambda<Func<T, T, T>>(addExpr, paramA, paramB).Compile(); } public ValueWrapper(T value) { v = value; public static ValueWrapper<T> operator +(ValueWrapper<T> a, ValueWrapper<T> b) { return new ValueWrapper<T>(addProxy(a.v, b.v));

Implementing Generic Complex, etc. (using ExprTree) using System.Linq.Expressions; struct ValueWrapper<T> { public T v; private static Func<T, T, T> addProxy; static ValueWrapper() { // Creates (a, b) => a + b lambda expression at runtime ParameterExpression paramA = Expression.Parameter(typeof(T), "a"); ParameterExpression paramB = Expression.Parameter(typeof(T), "b"); BinaryExpression addExpr = Expression.Add(paramA, paramB); addProxy = Expression.Lambda<Func<T, T, T>>(addExpr, paramA, paramB).Compile(); } public ValueWrapper(T value) { v = value; public static ValueWrapper<T> operator +(ValueWrapper<T> a, ValueWrapper<T> b) { return new ValueWrapper<T>(addProxy(a.v, b.v));

Serialization

System.Runtime.Serialization Serialization and Formatters namespace System.Runtime.Serialization.Formatters.Binary BinaryFormatter namespace System.Runtime.Serialization.Formatters.Soap assembly System.Runtime.Serialization.Formatters.Soap SoapFormatter Serializable objects: Must have SerializableAttribute defined All public and private member fields are serialized – this implies that all of them must be serializable, i.e. have SerializableAttribute defined Fields with NonSerializedAttribute are excluded from default serialization Can implement ISerializable interface to provide their custom serialization public interface IFormatter { void Serialize(Stream serializationStream, object graph); object Deserialize(Stream serializationStream); … }

Example: Serialization [Serializable] public class TestSimpleObject { int member1; string member2; string member3; double member4; [NonSerialized] string member5; public TestSimpleObject() member1 = 11; member2 = "hello"; member3 = "hello"; member4 = 3.14159265; member5 = "hello world!"; } [OnDeserializing] public void SetDefaults(StreamingContext ctx) { member5 = "DefaultValue"; public void Print() Console.WriteLine("member1 = '{0}'", member1); Console.WriteLine("member2 = '{0}'", member2); Console.WriteLine("member3 = '{0}'", member3); Console.WriteLine("member4 = '{0}'", member4); Console.WriteLine("member5 = '{0}'", member5);

Example: Serialization, cont. using System; using System.IO; using System.Runtime.Serialization; using System.Runtime.Serialization.Formatters.Soap; public class Test { public static void Main() TestSimpleObject obj = new TestSimpleObject(); obj.Print(); Stream stream = File.Open("data.xml", FileMode.Create); SoapFormatter formatter = new SoapFormatter(); formatter.Serialize(stream, obj); stream.Close(); obj = null; // stream = File.Open("data.xml", FileMode.Open); obj = (TestSimpleObject) formatter.Deserialize(stream); }

Example: Serialization, cont. Output of SoapFormatter: <SOAP-ENV:Envelope …> <SOAP-ENV:Body> <a1:TestSimpleObject id="ref-1" xmlns:a1="http://schemas.microsoft.com/clr/assem/Remoting1%2C%20Version%3D1.0.1256.35476%2C%20Culture%3Dneutral%2C%20PublicKeyToken%3Dnull"> <member1>11</member1> <member2 id="ref-3">hello</member2> <member3 href="#ref-3"/> <member4>3.14159265</member4> </a1:TestSimpleObject> </SOAP-ENV:Body> </SOAP-ENV:Envelope> Output of BinaryFormatter: