What’s new in C# 4? Kevin Pilch-Bisson [email_address] http://twitter.com/Pilchie
The Evolution of C# C# 1.0 C# 2.0 C# 3.0 Managed Code Generics Language Integrated Query
Trends
The Evolution of C# C# 1.0 C# 2.0 C# 3.0 Managed Code Generics Language Integrated Query C# 4.0 Dynamic Programming
C# 4.0 Language Innovations
.NET Dynamic Programming Python Binder Ruby Binder COM Binder JavaScript Binder Object Binder Dynamic Language Runtime Expression Trees Dynamic Dispatch Call Site Caching IronPython IronRuby C# VB.NET Others…
Dynamically Typed Objects Calculator  calc = GetCalculator(); int  sum = calc.Add(10, 20); object  calc = GetCalculator(); Type  calcType = calc.GetType(); object  res = calcType.InvokeMember( "Add" , BindingFlags.InvokeMethod,  null , new   object [] { 10, 20 }); int  sum = Convert.ToInt32(res); ScriptObject  calc = GetCalculator(); object  res = calc.Invoke( "Add" , 10, 20); int  sum =  Convert .ToInt32(res); dynamic  calc = GetCalculator(); int  sum = calc.Add(10, 20); Statically  typed to be dynamic Dynamic method invocation Dynamic conversion
Dynamically Typed Objects dynamic  calc = GetCalculator(); dynamic  sum = calc.Add( 10 ,  20 ); Another word for System.Object… When operand(s) are  dynamic … Member selection deferred to run-time Dispatch through COM, object itself, or C# binder Run-time type(s) substituted for  dynamic Compile-time type of operation is  dynamic … but with dynamic semantics
Dynamically Typed Objects public static class  Math { public   static   decimal  Abs( decimal  value); public   static   double  Abs( double  value); public   static   float  Abs( float  value); public   static   int  Abs( int  value); public   static   long  Abs( long  value); public   static   sbyte  Abs( sbyte  value); public   static   short  Abs( short  value); ... } double  x = 1.75; double  y =  Math .Abs(x);   dynamic  x = 1.75; dynamic  y =  Math .Abs(x);   dynamic  x = 2; dynamic  y =  Math .Abs(x);   Method chosen at compile-time: double Abs(double x) Method chosen at run-time:  double Abs(double x) Method chosen at run-time:  int Abs(int x)
Dynamically Typed Objects dynamic  d = GetDynamicObject(...); d.Foo(10,  "Hello" );  // Method invocation int  size = d.Width;  // Property access d.x = 25;  // Field access d[ "one" ] = d[ "two" ];  // Indexer access int  i = d + 3;  // Operator application string  s = d(5, 10);  // Delegate invocation
Dynamically Typed Objects
Optional and Named Parameters public   StreamReader  OpenTextFile( string  path, Encoding  encoding, bool  detectEncoding, int  bufferSize); public   StreamReader  OpenTextFile( string  path, Encoding  encoding, bool  detectEncoding); public   StreamReader  OpenTextFile( string  path, Encoding  encoding); public   StreamReader  OpenTextFile( string  path); Primary method Secondary overloads Call primary with default values
Optional and Named Parameters public   StreamReader  OpenTextFile( string  path, Encoding  encoding, bool  detectEncoding, int  bufferSize); public   StreamReader  OpenTextFile( string  path, Encoding  encoding =  null , bool  detectEncoding =  true , int  bufferSize = 1024); Optional parameters OpenTextFile( "foo.txt" ,  Encoding .UTF8); OpenTextFile( "foo.txt" ,  Encoding .UTF8, bufferSize: 4096); Named argument OpenTextFile( bufferSize: 4096, path:  "foo.txt" , detectEncoding:  false ); Named arguments must be last Non-optional must be specified Evaluated in order written Named arguments  can be in any order
Improved COM Interoperability object  fileName =  "Test.docx" ; object  missing  = System.Reflection. Missing .Value; doc.SaveAs( ref  fileName, ref  missing,  ref  missing,  ref  missing, ref  missing,  ref  missing,  ref  missing, ref  missing,  ref  missing,  ref  missing, ref  missing,  ref  missing,  ref  missing, ref  missing,  ref  missing,  ref  missing); doc.SaveAs( "Test.docx" );
Improved COM Interoperability Automatic object    dynamic mapping Optional and named parameters Indexed properties Optional “ref” modifier Interop type embedding (“No PIA”)
Improved COM Interoperability
Co- and Contra-variance void  Process( object [] objects) { … } string [] strings = GetStringArray(); Process(strings); void  Process( object [] objects) { objects[0] =  &quot;Hello&quot; ;  // Ok objects[1] =  new   Button ();  // Exception! } List < string > strings = GetStringList(); Process(strings); void  Process( IEnumerable < object > objects) { … } .NET arrays are co-variant … but  not safely co-variant Until now, C# generics have been  invariant void  Process( IEnumerable < object > objects) { // IEnumerable<T> is read-only and // therefore safely co-variant } C# 4.0 supports  safe  co- and contra-variance
Safe Co- and Contra-variance public   interface   IEnumerable <T> { IEnumerator <T> GetEnumerator(); } public   interface   IEnumerator <T> { T Current {  get ; } bool  MoveNext(); } public   interface   IEnumerable < out  T> { IEnumerator <T> GetEnumerator(); } public   interface   IEnumerator < out  T> { T Current {  get ; } bool  MoveNext(); } out  = Co-variant Output positions only IEnumerable < string > strings = GetStrings(); IEnumerable < object > objects = strings; Can be treated as less derived public   interface   IComparer <T> { int  Compare(T x, T y); } public   interface   IComparer < in  T> { int  Compare(T x, T y); } IComparer < object > objComp = GetComparer(); IComparer < string > strComp = objComp; in  = Contra-variant Input positions only Can be treated as more derived
Variance in C# 4.0 Supported for interface and delegate types “ Statically checked definition-site variance” Value types are always invariant IEnumerable<int>  is not  IEnumerable<object> Similar to existing rules for arrays ref and out parameters need invariant type
Variance in .NET Framework 4.0 System.Collections.Generic.IEnumerable<out T> System.Collections.Generic.IEnumerator<out T> System.Linq.IQueryable<out T> System.Collections.Generic.IComparer<in T> System.Collections.Generic.IEqualityComparer<in T> System.IComparable<in T> Interfaces System.Func<in T, …, out R> System.Action<in T, …> System.Predicate<in T> System.Comparison<in T> System.EventHandler<in T> Delegates
The Evolution of C# C# 1.0 C# 2.0 C# 3.0 Managed Code Generics Language Integrated Query C# 4.0 Dynamic Programming
Compiler as a Service Source code Source code Source File Source code Source code .NET Assembly Meta-programming Read-Eval-Print Loop Language Object Model DSL Embedding Compiler Compiler Class Field public Foo private string X
Compiler as a Service
Questions?
© 2010 Microsoft Corporation. All rights reserved. Microsoft, Windows, Windows Vista and other product names are or may be registered trademarks and/or trademarks in the U.S. and/or other countries. The information herein is for informational purposes only and represents the current view of Microsoft Corporation as of the date of this presentation.  Because Microsoft must respond to changing market conditions, it should not be interpreted to be a commitment on the part of Microsoft, and Microsoft cannot guarantee the accuracy of any information provided after the date of this presentation.  MICROSOFT MAKES NO WARRANTIES, EXPRESS, IMPLIED OR STATUTORY, AS TO THE INFORMATION IN THIS PRESENTATION. Required Slide

devLink - What's New in C# 4?

  • 1.
    What’s new inC# 4? Kevin Pilch-Bisson [email_address] http://twitter.com/Pilchie
  • 2.
    The Evolution ofC# C# 1.0 C# 2.0 C# 3.0 Managed Code Generics Language Integrated Query
  • 3.
  • 4.
    The Evolution ofC# C# 1.0 C# 2.0 C# 3.0 Managed Code Generics Language Integrated Query C# 4.0 Dynamic Programming
  • 5.
    C# 4.0 LanguageInnovations
  • 6.
    .NET Dynamic ProgrammingPython Binder Ruby Binder COM Binder JavaScript Binder Object Binder Dynamic Language Runtime Expression Trees Dynamic Dispatch Call Site Caching IronPython IronRuby C# VB.NET Others…
  • 7.
    Dynamically Typed ObjectsCalculator calc = GetCalculator(); int sum = calc.Add(10, 20); object calc = GetCalculator(); Type calcType = calc.GetType(); object res = calcType.InvokeMember( &quot;Add&quot; , BindingFlags.InvokeMethod, null , new object [] { 10, 20 }); int sum = Convert.ToInt32(res); ScriptObject calc = GetCalculator(); object res = calc.Invoke( &quot;Add&quot; , 10, 20); int sum = Convert .ToInt32(res); dynamic calc = GetCalculator(); int sum = calc.Add(10, 20); Statically typed to be dynamic Dynamic method invocation Dynamic conversion
  • 8.
    Dynamically Typed Objectsdynamic calc = GetCalculator(); dynamic sum = calc.Add( 10 , 20 ); Another word for System.Object… When operand(s) are dynamic … Member selection deferred to run-time Dispatch through COM, object itself, or C# binder Run-time type(s) substituted for dynamic Compile-time type of operation is dynamic … but with dynamic semantics
  • 9.
    Dynamically Typed Objectspublic static class Math { public static decimal Abs( decimal value); public static double Abs( double value); public static float Abs( float value); public static int Abs( int value); public static long Abs( long value); public static sbyte Abs( sbyte value); public static short Abs( short value); ... } double x = 1.75; double y = Math .Abs(x); dynamic x = 1.75; dynamic y = Math .Abs(x); dynamic x = 2; dynamic y = Math .Abs(x); Method chosen at compile-time: double Abs(double x) Method chosen at run-time: double Abs(double x) Method chosen at run-time: int Abs(int x)
  • 10.
    Dynamically Typed Objectsdynamic d = GetDynamicObject(...); d.Foo(10, &quot;Hello&quot; ); // Method invocation int size = d.Width; // Property access d.x = 25; // Field access d[ &quot;one&quot; ] = d[ &quot;two&quot; ]; // Indexer access int i = d + 3; // Operator application string s = d(5, 10); // Delegate invocation
  • 11.
  • 12.
    Optional and NamedParameters public StreamReader OpenTextFile( string path, Encoding encoding, bool detectEncoding, int bufferSize); public StreamReader OpenTextFile( string path, Encoding encoding, bool detectEncoding); public StreamReader OpenTextFile( string path, Encoding encoding); public StreamReader OpenTextFile( string path); Primary method Secondary overloads Call primary with default values
  • 13.
    Optional and NamedParameters public StreamReader OpenTextFile( string path, Encoding encoding, bool detectEncoding, int bufferSize); public StreamReader OpenTextFile( string path, Encoding encoding = null , bool detectEncoding = true , int bufferSize = 1024); Optional parameters OpenTextFile( &quot;foo.txt&quot; , Encoding .UTF8); OpenTextFile( &quot;foo.txt&quot; , Encoding .UTF8, bufferSize: 4096); Named argument OpenTextFile( bufferSize: 4096, path: &quot;foo.txt&quot; , detectEncoding: false ); Named arguments must be last Non-optional must be specified Evaluated in order written Named arguments can be in any order
  • 14.
    Improved COM Interoperabilityobject fileName = &quot;Test.docx&quot; ; object missing = System.Reflection. Missing .Value; doc.SaveAs( ref fileName, ref missing,  ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing); doc.SaveAs( &quot;Test.docx&quot; );
  • 15.
    Improved COM InteroperabilityAutomatic object  dynamic mapping Optional and named parameters Indexed properties Optional “ref” modifier Interop type embedding (“No PIA”)
  • 16.
  • 17.
    Co- and Contra-variancevoid Process( object [] objects) { … } string [] strings = GetStringArray(); Process(strings); void Process( object [] objects) { objects[0] = &quot;Hello&quot; ; // Ok objects[1] = new Button (); // Exception! } List < string > strings = GetStringList(); Process(strings); void Process( IEnumerable < object > objects) { … } .NET arrays are co-variant … but not safely co-variant Until now, C# generics have been invariant void Process( IEnumerable < object > objects) { // IEnumerable<T> is read-only and // therefore safely co-variant } C# 4.0 supports safe co- and contra-variance
  • 18.
    Safe Co- andContra-variance public interface IEnumerable <T> { IEnumerator <T> GetEnumerator(); } public interface IEnumerator <T> { T Current { get ; } bool MoveNext(); } public interface IEnumerable < out T> { IEnumerator <T> GetEnumerator(); } public interface IEnumerator < out T> { T Current { get ; } bool MoveNext(); } out = Co-variant Output positions only IEnumerable < string > strings = GetStrings(); IEnumerable < object > objects = strings; Can be treated as less derived public interface IComparer <T> { int Compare(T x, T y); } public interface IComparer < in T> { int Compare(T x, T y); } IComparer < object > objComp = GetComparer(); IComparer < string > strComp = objComp; in = Contra-variant Input positions only Can be treated as more derived
  • 19.
    Variance in C#4.0 Supported for interface and delegate types “ Statically checked definition-site variance” Value types are always invariant IEnumerable<int> is not IEnumerable<object> Similar to existing rules for arrays ref and out parameters need invariant type
  • 20.
    Variance in .NETFramework 4.0 System.Collections.Generic.IEnumerable<out T> System.Collections.Generic.IEnumerator<out T> System.Linq.IQueryable<out T> System.Collections.Generic.IComparer<in T> System.Collections.Generic.IEqualityComparer<in T> System.IComparable<in T> Interfaces System.Func<in T, …, out R> System.Action<in T, …> System.Predicate<in T> System.Comparison<in T> System.EventHandler<in T> Delegates
  • 21.
    The Evolution ofC# C# 1.0 C# 2.0 C# 3.0 Managed Code Generics Language Integrated Query C# 4.0 Dynamic Programming
  • 22.
    Compiler as aService Source code Source code Source File Source code Source code .NET Assembly Meta-programming Read-Eval-Print Loop Language Object Model DSL Embedding Compiler Compiler Class Field public Foo private string X
  • 23.
  • 24.
  • 25.
    © 2010 MicrosoftCorporation. All rights reserved. Microsoft, Windows, Windows Vista and other product names are or may be registered trademarks and/or trademarks in the U.S. and/or other countries. The information herein is for informational purposes only and represents the current view of Microsoft Corporation as of the date of this presentation. Because Microsoft must respond to changing market conditions, it should not be interpreted to be a commitment on the part of Microsoft, and Microsoft cannot guarantee the accuracy of any information provided after the date of this presentation. MICROSOFT MAKES NO WARRANTIES, EXPRESS, IMPLIED OR STATUTORY, AS TO THE INFORMATION IN THIS PRESENTATION. Required Slide

Editor's Notes

  • #4 Move towards more declarative styles of programming Domain specific, Functional Resurgence of dynamic programming languages Meta-programming Need for better concurrent programming models Distributed applications Many-core Trends cause fusing of ideas from previously distinct disciplines Functional in mainstream languages Static typing in dynamic languages Implicit typing in static languages Domain specific in every app HTML, SQL, XAML, XSLT The classic taxonomies are breaking down Going forward, mainstream GPLs will be multi-paradigm!
  • #26 08/10/10 17:56 © 2007 Microsoft Corporation. All rights reserved. Microsoft, Windows, Windows Vista and other product names are or may be registered trademarks and/or trademarks in the U.S. and/or other countries. The information herein is for informational purposes only and represents the current view of Microsoft Corporation as of the date of this presentation. Because Microsoft must respond to changing market conditions, it should not be interpreted to be a commitment on the part of Microsoft, and Microsoft cannot guarantee the accuracy of any information provided after the date of this presentation. MICROSOFT MAKES NO WARRANTIES, EXPRESS, IMPLIED OR STATUTORY, AS TO THE INFORMATION IN THIS PRESENTATION.