SlideShare a Scribd company logo
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

More Related Content

PPTX
What\'s New in C# 4.0
PPT
C tutorial
PPT
C tutorial
PPTX
Idiomatic C++
PPT
STL ALGORITHMS
ODP
OpenGurukul : Language : C++ Programming
PDF
C# / Java Language Comparison
What\'s New in C# 4.0
C tutorial
C tutorial
Idiomatic C++
STL ALGORITHMS
OpenGurukul : Language : C++ Programming
C# / Java Language Comparison

What's hot (18)

PPTX
PDF
Reflection in Go
PDF
Unmanaged Parallelization via P/Invoke
PDF
Design Patterns in Modern C++
PPTX
C++ Presentation
PDF
Introduction to Go programming language
PPTX
PDF
Golang and Eco-System Introduction / Overview
PPT
Console Io Operations
PDF
C++11 concurrency
PPT
Fantom on the JVM Devoxx09 BOF
PPTX
Kotlin as a Better Java
PPTX
Python The basics
PPTX
Go Programming Language (Golang)
PDF
C++11
PDF
Solid C++ by Example
PPTX
Python programming
PDF
Антихрупкий TypeScript | Odessa Frontend Meetup #17
Reflection in Go
Unmanaged Parallelization via P/Invoke
Design Patterns in Modern C++
C++ Presentation
Introduction to Go programming language
Golang and Eco-System Introduction / Overview
Console Io Operations
C++11 concurrency
Fantom on the JVM Devoxx09 BOF
Kotlin as a Better Java
Python The basics
Go Programming Language (Golang)
C++11
Solid C++ by Example
Python programming
Антихрупкий TypeScript | Odessa Frontend Meetup #17
Ad

Viewers also liked (6)

PPT
devLink - VB IDE Tips and Tricks for Visual Studio 2010
PPSX
Calculator and how to make it using VB 6.0
PPTX
Presentation on visual basic 6 (vb6)
PPT
Visual Basic Codes And Screen Designs
PDF
Hype vs. Reality: The AI Explainer
PDF
Study: The Future of VR, AR and Self-Driving Cars
devLink - VB IDE Tips and Tricks for Visual Studio 2010
Calculator and how to make it using VB 6.0
Presentation on visual basic 6 (vb6)
Visual Basic Codes And Screen Designs
Hype vs. Reality: The AI Explainer
Study: The Future of VR, AR and Self-Driving Cars
Ad

Similar to devLink - What's New in C# 4? (20)

PPT
Lo Mejor Del Pdc2008 El Futrode C#
PPTX
Whats New In C# 4 0 - NetPonto
PPTX
PDC Video on C# 4.0 Futures
PPSX
Introduction to c sharp 4.0 and dynamic
PPTX
2.dynamic
PPTX
Visual Studio 2010 and .NET 4.0 Overview
PPSX
Community Tech Days C# 4.0
PPT
Whats new in_csharp4
PPT
C sharp part2
PPTX
Dynamic Language Performance
PPS
Introduction to CSharp
PPT
Introduction to csharp
PPT
Introduction to-csharp-1229579367461426-1
PPT
Introduction to csharp
PPT
Introduction to csharp
PPT
Introduction To Csharp
PPTX
Overview Of .Net 4.0 Sanjay Vyas
PPT
New Features in .Net Framework 4.0 By Nyros Developer
PPTX
Dynamic in C# 4.0
PDF
1204csharp
Lo Mejor Del Pdc2008 El Futrode C#
Whats New In C# 4 0 - NetPonto
PDC Video on C# 4.0 Futures
Introduction to c sharp 4.0 and dynamic
2.dynamic
Visual Studio 2010 and .NET 4.0 Overview
Community Tech Days C# 4.0
Whats new in_csharp4
C sharp part2
Dynamic Language Performance
Introduction to CSharp
Introduction to csharp
Introduction to-csharp-1229579367461426-1
Introduction to csharp
Introduction to csharp
Introduction To Csharp
Overview Of .Net 4.0 Sanjay Vyas
New Features in .Net Framework 4.0 By Nyros Developer
Dynamic in C# 4.0
1204csharp

Recently uploaded (20)

PDF
Mobile App Security Testing_ A Comprehensive Guide.pdf
PDF
Optimiser vos workloads AI/ML sur Amazon EC2 et AWS Graviton
PPTX
Spectroscopy.pptx food analysis technology
PDF
Agricultural_Statistics_at_a_Glance_2022_0.pdf
PDF
Network Security Unit 5.pdf for BCA BBA.
PDF
Diabetes mellitus diagnosis method based random forest with bat algorithm
PDF
Blue Purple Modern Animated Computer Science Presentation.pdf.pdf
PDF
Advanced methodologies resolving dimensionality complications for autism neur...
PPTX
KOM of Painting work and Equipment Insulation REV00 update 25-dec.pptx
PPTX
Big Data Technologies - Introduction.pptx
PDF
The Rise and Fall of 3GPP – Time for a Sabbatical?
PDF
Dropbox Q2 2025 Financial Results & Investor Presentation
PDF
Profit Center Accounting in SAP S/4HANA, S4F28 Col11
PDF
Chapter 3 Spatial Domain Image Processing.pdf
PDF
Approach and Philosophy of On baking technology
PDF
Empathic Computing: Creating Shared Understanding
PPTX
Understanding_Digital_Forensics_Presentation.pptx
PDF
MIND Revenue Release Quarter 2 2025 Press Release
PPTX
Cloud computing and distributed systems.
PDF
Encapsulation theory and applications.pdf
Mobile App Security Testing_ A Comprehensive Guide.pdf
Optimiser vos workloads AI/ML sur Amazon EC2 et AWS Graviton
Spectroscopy.pptx food analysis technology
Agricultural_Statistics_at_a_Glance_2022_0.pdf
Network Security Unit 5.pdf for BCA BBA.
Diabetes mellitus diagnosis method based random forest with bat algorithm
Blue Purple Modern Animated Computer Science Presentation.pdf.pdf
Advanced methodologies resolving dimensionality complications for autism neur...
KOM of Painting work and Equipment Insulation REV00 update 25-dec.pptx
Big Data Technologies - Introduction.pptx
The Rise and Fall of 3GPP – Time for a Sabbatical?
Dropbox Q2 2025 Financial Results & Investor Presentation
Profit Center Accounting in SAP S/4HANA, S4F28 Col11
Chapter 3 Spatial Domain Image Processing.pdf
Approach and Philosophy of On baking technology
Empathic Computing: Creating Shared Understanding
Understanding_Digital_Forensics_Presentation.pptx
MIND Revenue Release Quarter 2 2025 Press Release
Cloud computing and distributed systems.
Encapsulation theory and applications.pdf

devLink - What's New in C# 4?

  • 1. What’s new in C# 4? Kevin Pilch-Bisson [email_address] http://twitter.com/Pilchie
  • 2. The Evolution of C# C# 1.0 C# 2.0 C# 3.0 Managed Code Generics Language Integrated Query
  • 4. The Evolution of C# C# 1.0 C# 2.0 C# 3.0 Managed Code Generics Language Integrated Query C# 4.0 Dynamic Programming
  • 5. C# 4.0 Language Innovations
  • 6. .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…
  • 7. Dynamically Typed Objects Calculator 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 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
  • 9. 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)
  • 10. Dynamically Typed Objects dynamic 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
  • 12. 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
  • 13. 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( &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 Interoperability object 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 Interoperability Automatic object  dynamic mapping Optional and named parameters Indexed properties Optional “ref” modifier Interop type embedding (“No PIA”)
  • 17. 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
  • 18. 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
  • 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 .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
  • 21. The Evolution of C# C# 1.0 C# 2.0 C# 3.0 Managed Code Generics Language Integrated Query C# 4.0 Dynamic Programming
  • 22. 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
  • 23. Compiler as a Service
  • 25. © 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

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.