C# 3.0 and 4.0
Click here to load reader
-
Upload
buu-nguyen -
Category
Technology
-
view
11.034 -
download
7
description
Transcript of C# 3.0 and 4.0
C# 3.0 & 4.0
Buu Nguyen
Buu Nguyen
• Microso6 MVP ASP.NET/IIS 2010, 2011 • Vice President of Technology, KMS Technology • IT Lecturer, RMIT University Vietnam • www.buunguyen.net/blog • @buunguyen
Agenda
• .NET and CLR • EvoluQon of C# • C# 3.0 and LINQ • C# 4.0 and Dynamic Programming
.NET AND CLR
.NET Framework
Common Language Run2me
Base Class Libraries
Common Type System & Common Intermediate Language
C# C++ VB.NET ... IronRuby
Visual Studio .NET
Common Language Specifica2on
CTS and CLS
• The Common Type System (CTS) specifies type rules for .NET code. CIL code complies with CTS.
• The Common Language SpecificaQon (CLS), a subset of CTS, assures language interoperability.
CIL
• Stack-‐based language • CIL manipulaQon enables
– Dynamic code generaQon, e.g. Fasterflect – Code instrumentaQon, e.g. test coverage tools – Decompilers, obfuscators…
InteresQng Type Concepts
• Value types vs. reference types • Stack-‐allocated vs. heap-‐allocated • Pass-‐by-‐value vs. pass-‐by-‐reference • Delegate vs. event types
More Types Post 1.x
• ParQal Types (C# 2.0) • Nullable Types (C# 2.0) • Generic Types (C# 2.0) • Dynamic Types (C# 4.0)
EVOLUTION OF C#
C# Language EvoluQon
C# 1.0
C# 2.0
C# 3.0
C# 4.0 C# 5.0
Generics (*) Nullable types Anonymous methods Yield return ParQal type StaQc class Namespace alias
LINQ (*) Auto-‐ properQes CollecQon iniQalizer Object iniQalizer Anonymous types Extension methods ParQal methods Lambda expressions Expression trees
Dynamic binding (*) Named arguments OpQonal parameters Generic variance Field-‐like events Robust locking Beeer COM interop
Async CaaS
DirecQon
• Concurrent programming – FuncQonal-‐style programming in C# 3.0 – PLINQ in .NET 4.0
• Dynamic programming – Dynamic binding in C# 4.0 and CaaS in C# 5.0
C# 3.0
Features • Implicitly-‐typed Local Variables • Implicitly-‐typed Arrays • Auto-‐implemented ProperQes • Object IniQalizers • CollecQon IniQalizers • ParQal Methods • Anonymous Types • Extension Methods • Lambda Expressions • Expression Trees
Implicitly-‐typed Local Variables
• Benefits – DRY (Don’t Repeat Yourself)
• SpecificaQons – Only apply to local variables – Must be iniQalized with an non-‐null expression
Implicitly-‐typed Arrays
• More DRY
Auto-‐implemented ProperQes
• AIP allows us to declare properQes with no implementaQon and no backing fields: compiler will generate code for them automaQcally
Object IniQalizers
• Combine construcQon and property assignments
CollecQon IniQalizers
• Like object iniQalizer, but this Qme applies to collecQons and maps
ParQal Methods
• Method contracts – Work inside parQal classes – Must be private & return void – Can be sta,c or non-‐sta,c – Cannot have out parameter (support ref nonetheless)
– Must not be virtual, abstract, override, sealed, or new
• Can omit the implementaQon – All calls will be omieed by the compiler
Anonymous Types
• This feature allows us to quickly create objects inside a method without declaring their corresponding class
Extension Methods
• This feature enable us to add methods to exisQng types. This is useful when – We don’t have access to source code of a type – The type is sealed and can’t be inherited
Lambda Expressions
• Shorter form of anonymous methods
Expression Trees
• Code as data – Enable LINQ-‐2-‐SQL, DLR… – Can be compiled to delegate – “Statement trees” are supported in .NET 4.0
LINQ
Show me some LINQ!
var people = from p in GetSalesPeople() where p.HireDate > hireDate select p; foreach (SalesPerson person in people) { Console.WriteLine(person.FirstName); }
LINQ in a Nutshell
Integrate query expressions into languages
Unified approach to query data
Declara2ve style of coding
Extensible via provider mechanism
How is LINQ Implemented?
• LINQ Query Expressions are translated to normal invocaQons to Standard Query Operators
var contacts = from c in customers where c.State == "WA" select new { c.Name, c.Phone };
var contacts = customers .Where(c => c.State == "WA") .Select(c => new { c.Name, c.Phone });
LINQ & C# 3.0
var contacts = from c in customers where c.State == "WA" select new { c.Name, c.Phone };
var contacts = customers .Where(c => c.State == "WA") .Select(c => new { c.Name, c.Phone });
Extension Method
Lambda Expression
Query Expression
Object Initializer Anonymous
Type
Implicitly-typed Local Variable
Where Do SQOs Come From?
§ Extensions methods for IEnumerable<T> defined in System.Linq.Enumerable
§ Building a LINQ-‐enabled data source is as simple as having your class implemenQng IEnumerable<T>
LINQ Clauses
from
where
select
group orderby
join
let
Structure of LINQ Queries
• from clause
First Line
• from, where, orderby, join, let clauses
Middle Lines
• select or group-by clause
Last Line
LINQ Architecture
Objects
<book> <Qtle/> <author/> <year/> <price/> </book>
XML RelaQonal DB
LINQ to Object
LINQ to XML
LINQ to ADO.NET
LINQ to SQL
LINQ to DataSet
LINQ to Entities
Others… Visual Basic C#
.NET Language-Integrated Query
IEnumerable<T>
Object Object Object Objects in Memory
from itemName in srcExpr where predExpr orderby (keyExpr (ascending | descending)) select selExpr ...
where
where orderby
where orderby select
Nothing
In Memory
from itemName in srcExpr where predExpr orderby (keyExpr (ascending | descending)) select selExpr ...
where
where orderby
where orderby select
“FROM [srcExpr] WHERE ...”
SELECT [selExpr] FROM [srcExpr] WHERE predExpr ORDER BY [keyExpr]”
FROM [srcExpr] WHERE predExpr ORDER BY [keyExpr]”
IQueryable<T>
Deferred vs. Non-‐deferred Operators
Deferred • Rule of thumb: LINQ query syntax
or IEnumerable<T> return • AsEnumerable, Cast,
Concat, DefaultIfEmpty, Distinct, Empty, Except, GroupBy, GroupJoin, Intersect, Join, OfType, OrderBy, OrderByDescending, Range, Repeat, Reverse, Select, SelectMany, Skip, SkipWhile, Take, TakeWhile, ThenBy, ThenByDescending, Union, Where
Non-‐deferred • Rule of thumb: scalar/single-‐value
return or conversion • Aggregate, All, Any,
Average, Contains, Count, ElementAt, ElementAtOrDefault, Last, LastOrDefault, LongCount, Max, Min, Single, SingleOrDefault, Sum, ToArray, ToDictionary, ToList, ToLookup
36
C# 4.0
Features Covered
• OpQonal Parameters • Named Arguments • Beeer COM Interop • Generic Variance • Robust Locking • Field-‐like Events
OPTIONAL PARAMETERS
How to implement MailMessage()?
Overloading
OpQonal Parameters
OpQonal Values
• Numeric and string literals • null • Compile-‐Qme constants • Enum members • default(T) • Parameterless constructor for structs
RestricQons
• OpQonal parameters must come a6er required parameters – Except for parameter array (empty array is used when not specified)
• OpQonal parameters can’t be ref or out
In Depth: DefiniQon Site
In Depth: Call Site
Consequence
• OpQonal values are part of the published API, if they are changed, client code must be recompiled. Worse, the compiler won’t warn you if you don’t change.
NAMED ARGUMENTS
How to Avoid the Comments?
Object IniQalizer
Named Arguments
…Named Arguments
RestricQons
• PosiQonal arguments must come before named arguments
Under the Hood
• The compiler just reorders, that’s all
Consequence
• Parameter names are part of the published API, if they are changed, client code must be changed.
BETTER COM INTEROPERABILITY
How Do You Like This?
#1: Omit ref
#2: OpQonal Parameters
GENERIC VARIANCE
Is This Okay?
No, because…
Generic Covariance
• Generic covariance reserves assignment compaQbility on generic types – If T1 is a subtype of T2, GT<T1> behaves like subtype of GT<T2> on assignment
• Safe only when GT doesn’t “take in” any T
Example
On Delegate
Is This Okay?
No, because…
Generic Contravariance
• Generic covariance reverses assignment compaQbility on generic types – If T1 is a subtype of T2, GT<T1> behaves like supertype of GT<T2> on assignment
• Safe only when GT doesn’t return any T
Example
On Delegate
Under the Hood
ROBUST LOCKING
Problem
If the thread is aborted a>er the lock is acquired but before we enter the try block, we won’t have released the lock.
SoluQon
FIELD-‐LIKE EVENTS
The Problem
Lock on ‘this’ is bad. Lock on ‘type’ is bad.
The SoluQon
A simple lock would work, but this is beeer because it’s lock-‐free.
DYNAMIC BINDING
WHAT IS DYNAMIC BINDING
StaQc vs. Dynamic Binding
Sta2c Binding • Compiler figures out which
members to call (binding process) – Defer subtype polymorphic
resoluQon Qll run Qme
Dynamic Biding • All bindings happen during
run Qme
StaQc Binding
Benefits of StaQc Binding
• Type and name errors are detected at compile Qme, e.g. – Invoke non-‐existent members – Pass in arguments with wrong type – Perform illegal cast
Dynamic Binding
HOW IS IT IMPLEMENTED?
Run Time Binding
• Instead of aeempQng binding and generaQng CIL, the compiler packages the call and sends it to the Dynamic Language RunQme
• At run Qme, the DLR performs binding and execuQon
Under the Hood
becomes
The Dynamic Language RunQme
Process in a nutshell
C# dynamic
Call Sites
C# Binder
Expression Tree
Delegate
Dynamic Objects
compiled
builds
emits
DLR
uses
builds
cached
User-‐defined or from other languages
IDynamicMetaObjectProvider
Dynamic Type in CIL
WHEN DO WE NEED IT?
Key Scenarios
1. Access a member with only knowledge of its name, arguments, and target object
2. Interop with dynamic languages, e.g. IronRuby, IronPython
3. Have the target object decide how to respond to a call at run Qme
Key Scenarios
1. Access a member with only knowledge of its name, arguments, and target object
2. Interop with dynamic languages, e.g. IronRuby, IronPython
3. Have the target object decide how to respond to a call at run Qme
Access Members
ReflecQon
Dynamic Type
Single vs. MulQple Dispatch
Single Dispatch • Method is selected based
on the runQme type of the target object
Mul2ple Dispatch • Method is selected based
on both the runQme type of the target object and those of the method’s arguments
Dispatch Example
Key Scenarios
1. Access a member with only knowledge of its name, arguments, and target object
2. Interop with dynamic languages, e.g. IronRuby, IronPython
3. Have the target object decide how to respond to a call at run Qme
Invoke Ruby Code
Work with Ruby Class
Work with method_missing
Key Scenarios
1. Access a member with only knowledge of its name, arguments, and target object
2. Interop with dynamic languages, e.g. IronRuby, IronPython
3. Have the target object decide how to respond to a call at run Qme
The Magic Interface
IDynamicMetaObjectProvider
DynamicObject
ExpandoObject
ExpandoObject
DynamicObject’s OperaQons Name Descrip2on
TryGetMember Member geeer, e.g. obj.Name
TrySetMember Member seeer, e.g. obj.age = 10
TryDeleteMember Member removal (no equivalent in C#)
TryInvokeMember Method invocaQon, e.g. obj.Invoke()
TryConvert CasQng, e.g. (int)obj
TryCreateInstance Object creaQon (no equivalent in C#)
TryInvoke Self invocaQon, e.g. obj(10)
TryBinaryOperaQon Binary operaQon, e.g. obj + 10
TryUnaryOperaQon Unary operaQon, e.g. !obj
TryGetIndex Indexer geeer, e.g. obj[“key”]
TrySetIndex Indexer seeer, e.g. obj[“key”] = value
TryDeleteIndex Indexer removal (no equivalent in C#)
Log Seeers & InvocaQons
StaQcInvoker
StaQcInvoker
Close to the metal
…Close to the metal
…Close to the metal
RESTRICTIONS
RestricQon #1
• Doesn’t work with extension methods
RestricQon #2
• Can’t resolve staQc members or constructors on a dynamic type
RestricQon #3
• Method groups, anonymous methods and lambda expressions to be casted to exact type
RestricQon #4