C# 3.0 and 4.0

11,556 views

Published on

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

Published in: Technology
0 Comments
8 Likes
Statistics
Notes
  • Be the first to comment

No Downloads
Views
Total views
11,556
On SlideShare
0
From Embeds
0
Number of Embeds
7,296
Actions
Shares
0
Downloads
285
Comments
0
Likes
8
Embeds 0
No embeds

No notes for slide

C# 3.0 and 4.0

  1. 1. C#  3.0  &  4.0   Buu  Nguyen  
  2. 2. 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  
  3. 3. Agenda  •  .NET  and  CLR  •  EvoluQon  of  C#  •  C#  3.0  and  LINQ  •  C#  4.0  and  Dynamic  Programming  
  4. 4. .NET  AND  CLR  
  5. 5. .NET  Framework  C#   C++   VB.NET   IronRuby   ...   Visual  Studio  .NET   Common  Type  System  &     Common  Intermediate  Language     Common  Language  Specifica2on   Base  Class  Libraries   Common  Language  Run2me  
  6. 6. 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.  
  7. 7. CIL  •  Stack-­‐based  language  •  CIL  manipulaQon  enables   –  Dynamic  code  generaQon,  e.g.  Fasterflect   –  Code  instrumentaQon,  e.g.  test  coverage  tools   –  Decompilers,  obfuscators…  
  8. 8. InteresQng  Type  Concepts  •  Value  types  vs.  reference  types  •  Stack-­‐allocated  vs.  heap-­‐allocated  •  Pass-­‐by-­‐value  vs.  pass-­‐by-­‐reference  •  Delegate  vs.  event  types  
  9. 9. 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)  
  10. 10. EVOLUTION  OF  C#  
  11. 11. C#  Language  EvoluQon   C#  5.0   C#  4.0     Async   CaaS   Dynamic  binding  (*)   C#  3.0   Named  arguments   OpQonal  parameters   LINQ  (*)   Generic  variance   Auto-­‐  properQes   C#  2.0   CollecQon  iniQalizer   Field-­‐like  events   Robust  locking   Object  iniQalizer   Generics  (*)   Beeer  COM  interop   Anonymous  types   Nullable  types   Extension  methods   Anonymous  methods  C#  1.0   Yield  return   ParQal  methods   Lambda  expressions   ParQal  type   Expression  trees   StaQc  class   Namespace  alias  
  12. 12. 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  
  13. 13. C#  3.0  
  14. 14. 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  
  15. 15. Implicitly-­‐typed  Local  Variables  •  Benefits   –  DRY  (Don’t  Repeat  Yourself)  •  SpecificaQons   –  Only  apply  to  local  variables   –  Must  be  iniQalized  with  an  non-­‐null  expression    
  16. 16. Implicitly-­‐typed  Arrays  •  More  DRY  
  17. 17. Auto-­‐implemented  ProperQes  •  AIP  allows  us  to  declare  properQes  with  no   implementaQon  and  no  backing  fields:   compiler  will  generate  code  for  them   automaQcally                      
  18. 18. Object  IniQalizers  •  Combine  construcQon  and  property  assignments
  19. 19. CollecQon  IniQalizers  •  Like  object  iniQalizer,  but  this  Qme  applies  to   collecQons  and  maps  
  20. 20. 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  
  21. 21. Anonymous  Types  •  This  feature  allows  us  to  quickly  create  objects   inside  a  method  without  declaring  their   corresponding  class  
  22. 22. 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  
  23. 23. Lambda  Expressions  •  Shorter  form  of  anonymous  methods
  24. 24. Expression  Trees  •  Code  as  data   –  Enable  LINQ-­‐2-­‐SQL,  DLR…   –  Can  be  compiled  to  delegate   –  “Statement  trees”  are  supported  in  .NET  4.0  
  25. 25. LINQ  
  26. 26. 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);}
  27. 27. LINQ  in  a  Nutshell  Integrate  query  expressions  into  languages  Unified  approach  to  query  data  Declara2ve  style  of  coding  Extensible  via  provider  mechanism  
  28. 28. 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 });
  29. 29. LINQ  &  C#  3.0   var contacts = from c in customers Query Expression where c.State == "WA" select new { c.Name, c.Phone }; Implicitly-typed Local Variable Lambda Expression var contacts = customers .Where(c => c.State == "WA") .Select(c => new { c.Name, c.Phone });Extension Object Method Initializer Anonymous Type
  30. 30. 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>    
  31. 31. LINQ  Clauses   from     let   where  join   select   orderby   group  
  32. 32. Structure  of  LINQ  Queries  First  Line  • from  clause  Middle  Lines  • from,  where,  orderby,  join,  let  clauses  Last  Line  • select  or  group-by  clause  
  33. 33. LINQ  Architecture  Visual Basic C# Others… .NET Language-Integrated Query LINQ to ADO.NET LINQ LINQ LINQ LINQ LINQ to XMLto Object to SQL to DataSet to Entities <book>          <Qtle/>          <author/>          <year/>          <price/>   </book>   Objects   RelaQonal  DB   XML  
  34. 34. IEnumerable<T>   from  itemName  in  srcExpr  Object   where  predExpr   Object   orderby  (keyExpr  (ascending  |  descending))   Object   Objects  in   Memory   select  selExpr   ...   where   where   orderby   where   orderby   select  
  35. 35.   IQueryable<T>  Nothing     In     from  itemName  in  srcExpr   where  predExpr   orderby  (keyExpr  (ascending  |  descending))  Memory   select  selExpr   ...   “FROM  [srcExpr]  WHERE  ...”  where   FROM  [srcExpr]  WHERE  predExpr  where   ORDER  BY  [keyExpr]”  orderby   SELECT  [selExpr]  where   FROM  [srcExpr]  WHERE  predExpr   ORDER  BY  [keyExpr]”  orderby   select  
  36. 36. Deferred  vs.  Non-­‐deferred  Operators  Deferred   Non-­‐deferred  •  Rule  of  thumb:  LINQ  query  syntax     •  Rule  of  thumb:  scalar/single-­‐value   or  IEnumerable<T>  return   return  or  conversion  •  AsEnumerable, Cast, •  Aggregate, All, Any, Concat, DefaultIfEmpty, Average, Contains, Count, Distinct, Empty, Except, ElementAt, GroupBy, GroupJoin, ElementAtOrDefault, Last, Intersect, Join, OfType, LastOrDefault, LongCount, OrderBy, Max, Min, Single, OrderByDescending, Range, SingleOrDefault, Sum, Repeat, Reverse, Select, ToArray, ToDictionary, SelectMany, Skip, ToList, ToLookup SkipWhile, Take, TakeWhile, ThenBy, ThenByDescending, Union, Where 36  
  37. 37. C#  4.0  
  38. 38. Features  Covered  •  OpQonal  Parameters  •  Named  Arguments  •  Beeer  COM  Interop  •  Generic  Variance  •  Robust  Locking  •  Field-­‐like  Events  
  39. 39. OPTIONAL  PARAMETERS  
  40. 40. How  to  implement  MailMessage()?  
  41. 41. Overloading  
  42. 42. OpQonal  Parameters  
  43. 43. OpQonal  Values  •  Numeric  and  string  literals  •  null  •  Compile-­‐Qme  constants  •  Enum  members  •  default(T)  •  Parameterless  constructor  for  structs  
  44. 44. 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  
  45. 45. In  Depth:  DefiniQon  Site  
  46. 46. In  Depth:  Call  Site  
  47. 47. 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.  
  48. 48. NAMED  ARGUMENTS  
  49. 49. How  to  Avoid  the  Comments?  
  50. 50. Object  IniQalizer  
  51. 51. Named  Arguments  
  52. 52. …Named  Arguments  
  53. 53. RestricQons  •  PosiQonal  arguments  must  come  before   named  arguments  
  54. 54. Under  the  Hood  •  The  compiler  just  reorders,  that’s  all  
  55. 55. Consequence  •  Parameter  names  are  part  of  the  published   API,  if  they  are  changed,  client  code  must  be   changed.  
  56. 56. BETTER  COM  INTEROPERABILITY  
  57. 57. How  Do  You  Like  This?  
  58. 58. #1:  Omit  ref  
  59. 59. #2:  OpQonal  Parameters  
  60. 60. GENERIC  VARIANCE  
  61. 61. Is  This  Okay?  
  62. 62. No,  because…  
  63. 63. 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  
  64. 64. Example  
  65. 65. On  Delegate  
  66. 66. Is  This  Okay?  
  67. 67. No,  because…  
  68. 68. 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  
  69. 69. Example  
  70. 70. On  Delegate  
  71. 71. Under  the  Hood  
  72. 72. ROBUST  LOCKING  
  73. 73. 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.  
  74. 74. SoluQon  
  75. 75. FIELD-­‐LIKE  EVENTS  
  76. 76. The  Problem  Lock  on  ‘this’  is  bad.    Lock  on  ‘type’  is  bad.  
  77. 77. The  SoluQon  A  simple  lock  would  work,  but  this  is  beeer  because  it’s  lock-­‐free.  
  78. 78. DYNAMIC  BINDING  
  79. 79. WHAT  IS  DYNAMIC  BINDING  
  80. 80. StaQc  vs.  Dynamic  Binding  Sta2c  Binding   Dynamic  Biding  •  Compiler  figures  out  which   •  All  bindings  happen  during   members  to  call  (binding   run  Qme   process)   –  Defer  subtype  polymorphic   resoluQon  Qll  run  Qme  
  81. 81. StaQc  Binding  
  82. 82. 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  
  83. 83. Dynamic  Binding  
  84. 84. HOW  IS  IT  IMPLEMENTED?  
  85. 85. 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  
  86. 86. Under  the  Hood  becomes  
  87. 87. The  Dynamic  Language  RunQme  
  88. 88. Process  in  a  nutshell   C#   dynamic   Dynamic   builds   Objects   User-­‐defined  or  from  other  languages   compiled   uses   IDynamicMetaObjectProvider   Call  Sites   cached   Delegate   Expression   emits   Tree  DLR   C#  Binder   builds  
  89. 89. Dynamic  Type  in  CIL  
  90. 90. WHEN  DO  WE  NEED  IT?  
  91. 91. 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  
  92. 92. 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  
  93. 93. Access  Members  
  94. 94. ReflecQon  
  95. 95. Dynamic  Type  
  96. 96. Single  vs.  MulQple  Dispatch  Single  Dispatch   Mul2ple  Dispatch  •  Method  is  selected  based   •  Method  is  selected  based   on  the  runQme  type  of  the   on  both  the  runQme  type  of   target  object   the  target  object  and  those   of  the  method’s  arguments  
  97. 97. Dispatch  Example  
  98. 98. 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  
  99. 99. Invoke  Ruby  Code  
  100. 100. Work  with  Ruby  Class  
  101. 101. Work  with  method_missing  
  102. 102. 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  
  103. 103. The  Magic  Interface  IDynamicMetaObjectProvider   ExpandoObject   DynamicObject  
  104. 104. ExpandoObject  
  105. 105. 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#)  
  106. 106. Log  Seeers  &  InvocaQons  
  107. 107. StaQcInvoker  
  108. 108. StaQcInvoker  
  109. 109. Close  to  the  metal  
  110. 110. …Close  to  the  metal  
  111. 111. …Close  to  the  metal  
  112. 112. RESTRICTIONS  
  113. 113. RestricQon  #1  •  Doesn’t  work  with  extension  methods  
  114. 114. RestricQon  #2  •  Can’t  resolve  staQc  members  or  constructors   on  a  dynamic  type  
  115. 115. RestricQon  #3  •  Method  groups,  anonymous  methods  and  lambda   expressions  to  be  casted  to  exact  type  
  116. 116. RestricQon  #4  

×