C# 3.0 and 4.0

116

Click here to load reader

description

Slides I to train C# to Microsoft customers in June 2011

Transcript of C# 3.0 and 4.0

Page 1: C# 3.0 and 4.0

C#  3.0  &  4.0  

Buu  Nguyen  

Page 2: C# 3.0 and 4.0

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  

Page 3: C# 3.0 and 4.0

Agenda  

•  .NET  and  CLR  •  EvoluQon  of  C#  •  C#  3.0  and  LINQ  •  C#  4.0  and  Dynamic  Programming  

Page 4: C# 3.0 and 4.0

.NET  AND  CLR  

Page 5: C# 3.0 and 4.0

.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  

Page 6: C# 3.0 and 4.0

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.  

Page 7: C# 3.0 and 4.0

CIL  

•  Stack-­‐based  language  •  CIL  manipulaQon  enables  

– Dynamic  code  generaQon,  e.g.  Fasterflect  – Code  instrumentaQon,  e.g.  test  coverage  tools  – Decompilers,  obfuscators…  

Page 8: C# 3.0 and 4.0

InteresQng  Type  Concepts  

•  Value  types  vs.  reference  types  •  Stack-­‐allocated  vs.  heap-­‐allocated  •  Pass-­‐by-­‐value  vs.  pass-­‐by-­‐reference  •  Delegate  vs.  event  types  

Page 9: C# 3.0 and 4.0

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)  

Page 10: C# 3.0 and 4.0

EVOLUTION  OF  C#  

Page 11: C# 3.0 and 4.0

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  

Page 12: C# 3.0 and 4.0

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  

Page 13: C# 3.0 and 4.0

C#  3.0  

Page 14: C# 3.0 and 4.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  

Page 15: C# 3.0 and 4.0

Implicitly-­‐typed  Local  Variables  

•  Benefits  – DRY  (Don’t  Repeat  Yourself)  

•  SpecificaQons  – Only  apply  to  local  variables  – Must  be  iniQalized  with  an  non-­‐null  expression  

 

Page 16: C# 3.0 and 4.0

Implicitly-­‐typed  Arrays  

•  More  DRY  

Page 17: C# 3.0 and 4.0

Auto-­‐implemented  ProperQes  

•  AIP  allows  us  to  declare  properQes  with  no  implementaQon  and  no  backing  fields:  compiler  will  generate  code  for  them  automaQcally  

                   

Page 18: C# 3.0 and 4.0

Object  IniQalizers  

•  Combine  construcQon  and  property  assignments

Page 19: C# 3.0 and 4.0

CollecQon  IniQalizers  

•  Like  object  iniQalizer,  but  this  Qme  applies  to  collecQons  and  maps  

Page 20: C# 3.0 and 4.0

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  

Page 21: C# 3.0 and 4.0

Anonymous  Types  

•  This  feature  allows  us  to  quickly  create  objects  inside  a  method  without  declaring  their  corresponding  class  

Page 22: C# 3.0 and 4.0

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  

Page 23: C# 3.0 and 4.0

Lambda  Expressions  

•  Shorter  form  of  anonymous  methods

Page 24: C# 3.0 and 4.0

Expression  Trees  

•  Code  as  data  –  Enable  LINQ-­‐2-­‐SQL,  DLR…  –  Can  be  compiled  to  delegate  –  “Statement  trees”  are  supported  in  .NET  4.0  

Page 25: C# 3.0 and 4.0

LINQ  

Page 26: C# 3.0 and 4.0

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); }

Page 27: C# 3.0 and 4.0

LINQ  in  a  Nutshell  

Integrate  query  expressions  into  languages  

Unified  approach  to  query  data  

Declara2ve  style  of  coding  

Extensible  via  provider  mechanism  

Page 28: C# 3.0 and 4.0

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 });

Page 29: C# 3.0 and 4.0

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

Page 30: C# 3.0 and 4.0

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>  

 

Page 31: C# 3.0 and 4.0

LINQ  Clauses  

from    

where  

select  

group  orderby  

join  

let  

Page 32: C# 3.0 and 4.0

Structure  of  LINQ  Queries  

• from  clause  

First  Line  

• from,  where,  orderby,  join,  let  clauses  

Middle  Lines  

• select  or  group-by  clause  

Last  Line  

Page 33: C# 3.0 and 4.0

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

Page 34: C# 3.0 and 4.0

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  

Page 35: C# 3.0 and 4.0

   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>  

Page 36: C# 3.0 and 4.0

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  

Page 37: C# 3.0 and 4.0

C#  4.0  

Page 38: C# 3.0 and 4.0

Features  Covered  

•  OpQonal  Parameters  •  Named  Arguments  •  Beeer  COM  Interop  •  Generic  Variance  •  Robust  Locking  •  Field-­‐like  Events  

Page 39: C# 3.0 and 4.0

OPTIONAL  PARAMETERS  

Page 40: C# 3.0 and 4.0

How  to  implement  MailMessage()?  

Page 41: C# 3.0 and 4.0

Overloading  

Page 42: C# 3.0 and 4.0

OpQonal  Parameters  

Page 43: C# 3.0 and 4.0

OpQonal  Values  

•  Numeric  and  string  literals  •  null  •  Compile-­‐Qme  constants  •  Enum  members  •  default(T)  •  Parameterless  constructor  for  structs  

Page 44: C# 3.0 and 4.0

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  

Page 45: C# 3.0 and 4.0

In  Depth:  DefiniQon  Site  

Page 46: C# 3.0 and 4.0

In  Depth:  Call  Site  

Page 47: C# 3.0 and 4.0

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.  

Page 48: C# 3.0 and 4.0

NAMED  ARGUMENTS  

Page 49: C# 3.0 and 4.0

How  to  Avoid  the  Comments?  

Page 50: C# 3.0 and 4.0

Object  IniQalizer  

Page 51: C# 3.0 and 4.0

Named  Arguments  

Page 52: C# 3.0 and 4.0

…Named  Arguments  

Page 53: C# 3.0 and 4.0

RestricQons  

•  PosiQonal  arguments  must  come  before  named  arguments  

Page 54: C# 3.0 and 4.0

Under  the  Hood  

•  The  compiler  just  reorders,  that’s  all  

Page 55: C# 3.0 and 4.0

Consequence  

•  Parameter  names  are  part  of  the  published  API,  if  they  are  changed,  client  code  must  be  changed.  

Page 56: C# 3.0 and 4.0

BETTER  COM  INTEROPERABILITY  

Page 57: C# 3.0 and 4.0

How  Do  You  Like  This?  

Page 58: C# 3.0 and 4.0

#1:  Omit  ref  

Page 59: C# 3.0 and 4.0

#2:  OpQonal  Parameters  

Page 60: C# 3.0 and 4.0

GENERIC  VARIANCE  

Page 61: C# 3.0 and 4.0

Is  This  Okay?  

Page 62: C# 3.0 and 4.0

No,  because…  

Page 63: C# 3.0 and 4.0

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  

Page 64: C# 3.0 and 4.0

Example  

Page 65: C# 3.0 and 4.0

On  Delegate  

Page 66: C# 3.0 and 4.0

Is  This  Okay?  

Page 67: C# 3.0 and 4.0

No,  because…  

Page 68: C# 3.0 and 4.0

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  

Page 69: C# 3.0 and 4.0

Example  

Page 70: C# 3.0 and 4.0

On  Delegate  

Page 71: C# 3.0 and 4.0

Under  the  Hood  

Page 72: C# 3.0 and 4.0

ROBUST  LOCKING  

Page 73: C# 3.0 and 4.0

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.  

Page 74: C# 3.0 and 4.0

SoluQon  

Page 75: C# 3.0 and 4.0

FIELD-­‐LIKE  EVENTS  

Page 76: C# 3.0 and 4.0

The  Problem  

Lock  on  ‘this’  is  bad.    Lock  on  ‘type’  is  bad.  

Page 77: C# 3.0 and 4.0

The  SoluQon  

A  simple  lock  would  work,  but  this  is  beeer  because  it’s  lock-­‐free.  

Page 78: C# 3.0 and 4.0

DYNAMIC  BINDING  

Page 79: C# 3.0 and 4.0

WHAT  IS  DYNAMIC  BINDING  

Page 80: C# 3.0 and 4.0

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  

Page 81: C# 3.0 and 4.0

StaQc  Binding  

Page 82: C# 3.0 and 4.0

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  

Page 83: C# 3.0 and 4.0

Dynamic  Binding  

Page 84: C# 3.0 and 4.0

HOW  IS  IT  IMPLEMENTED?  

Page 85: C# 3.0 and 4.0

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  

Page 86: C# 3.0 and 4.0

Under  the  Hood  

becomes  

Page 87: C# 3.0 and 4.0

The  Dynamic  Language  RunQme  

Page 88: C# 3.0 and 4.0

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  

Page 89: C# 3.0 and 4.0

Dynamic  Type  in  CIL  

Page 90: C# 3.0 and 4.0

WHEN  DO  WE  NEED  IT?  

Page 91: C# 3.0 and 4.0

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  

Page 92: C# 3.0 and 4.0

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  

Page 93: C# 3.0 and 4.0

Access  Members  

Page 94: C# 3.0 and 4.0

ReflecQon  

Page 95: C# 3.0 and 4.0

Dynamic  Type  

Page 96: C# 3.0 and 4.0

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  

Page 97: C# 3.0 and 4.0

Dispatch  Example  

Page 98: C# 3.0 and 4.0

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  

Page 99: C# 3.0 and 4.0

Invoke  Ruby  Code  

Page 100: C# 3.0 and 4.0

Work  with  Ruby  Class  

Page 101: C# 3.0 and 4.0

Work  with  method_missing  

Page 102: C# 3.0 and 4.0

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  

Page 103: C# 3.0 and 4.0

The  Magic  Interface  

IDynamicMetaObjectProvider  

DynamicObject  

ExpandoObject  

Page 104: C# 3.0 and 4.0

ExpandoObject  

Page 105: C# 3.0 and 4.0

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#)  

Page 106: C# 3.0 and 4.0

Log  Seeers  &  InvocaQons  

Page 107: C# 3.0 and 4.0

StaQcInvoker  

Page 108: C# 3.0 and 4.0

StaQcInvoker  

Page 109: C# 3.0 and 4.0

Close  to  the  metal  

Page 110: C# 3.0 and 4.0

…Close  to  the  metal  

Page 111: C# 3.0 and 4.0

…Close  to  the  metal  

Page 112: C# 3.0 and 4.0

RESTRICTIONS  

Page 113: C# 3.0 and 4.0

RestricQon  #1  

•  Doesn’t  work  with  extension  methods  

Page 114: C# 3.0 and 4.0

RestricQon  #2  

•  Can’t  resolve  staQc  members  or  constructors  on  a  dynamic  type  

Page 115: C# 3.0 and 4.0

RestricQon  #3  

•  Method  groups,  anonymous  methods  and  lambda  expressions  to  be  casted  to  exact  type  

Page 116: C# 3.0 and 4.0

RestricQon  #4