The Future of C#TL16 Anders Hejlsberg	Technical Fellow	Microsoft Corporation
The Evolution of C#C# 3.0Language Integrated QueryC# 2.0GenericsC# 1.0Managed Code
Trends
Declarative ProgrammingWhatHowImperativeDeclarative
Dynamic vs. Static
Concurrency
Co-Evolution
The Evolution of C#C# 4.0Dynamic ProgrammingC# 3.0Language Integrated QueryC# 2.0GenericsC# 1.0Managed Code
Dynamically Typed ObjectsOptional and Named ParametersImproved COM InteroperabilityCo- and Contra-varianceC# 4.0 Language Innovations
.NET Dynamic ProgrammingIronPythonIronRubyC#VB.NETOthers…Dynamic Language RuntimeExpression TreesDynamic DispatchCall Site CachingPythonBinderRubyBinderCOMBinderJavaScriptBinderObjectBinder
Dynamically Typed ObjectsCalculator calc = GetCalculator();int sum = calc.Add(10, 20);object calc = GetCalculator();TypecalcType = calc.GetType();object res = calcType.InvokeMember("Add",BindingFlags.InvokeMethod, null,newobject[] { 10, 20 });int sum = Convert.ToInt32(res);ScriptObject calc = GetCalculator();object res = calc.Invoke("Add", 10, 20);int sum = Convert.ToInt32(res);Statically typed to be dynamicdynamic calc = GetCalculator();int sum = calc.Add(10, 20);Dynamic method invocationDynamic conversion
Dynamically Typed ObjectsCompile-time typedynamicRun-time typeSystem.Int32dynamic x = 1;dynamic y = "Hello";dynamic z = newList<int> { 1, 2, 3 };When operand(s) are dynamic… Member selection deferred to run-time
 At run-time, actual type(s) substituted for dynamic
 Static result type of operation is dynamicpublic static class Math{   publicstaticdecimal Abs(decimal value);   publicstaticdouble Abs(double value);   publicstaticfloat Abs(float value);   publicstaticint Abs(int value);   publicstaticlong Abs(long value);   publicstaticsbyte Abs(sbyte value);   publicstaticshort Abs(short value);   ...}double x = 1.75;double y = Math.Abs(x);dynamic x = 1.75;dynamic y = Math.Abs(x);Dynamically Typed ObjectsMethod 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)dynamic x = 2;dynamic y = Math.Abs(x);
Dynamically Typed Objectsdemo
IDynamicObjectpublicabstractclassDynamicObject : IDynamicObject{publicvirtualobjectGetMember(GetMemberBinder info);publicvirtualobjectSetMember(SetMemberBinder info, object value);publicvirtualobjectDeleteMember(DeleteMemberBinder info); publicvirtualobjectUnaryOperation(UnaryOperationBinder info);publicvirtualobjectBinaryOperation(BinaryOperationBinder info, objectarg);publicvirtualobject Convert(ConvertBinder info); publicvirtualobject Invoke(InvokeBinder info, object[] args);publicvirtualobjectInvokeMember(InvokeMemberBinder info, object[] args);publicvirtualobjectCreateInstance(CreateInstanceBinder info, object[] args); publicvirtualobjectGetIndex(GetIndexBinder info, object[] indices);publicvirtualobjectSetIndex(SetIndexBinder info, object[] indices, object value);publicvirtualobjectDeleteIndex(DeleteIndexBinder info, object[] indices); publicMetaObjectIDynamicObject.GetMetaObject();}
Implementing IDynamicObjectdemo
Optional and Named ParametersPrimary methodpublicStreamReaderOpenTextFile(    string path,    Encodingencoding,booldetectEncoding,intbufferSize);Secondary overloadspublicStreamReaderOpenTextFile(    string path,    Encodingencoding,booldetectEncoding);publicStreamReaderOpenTextFile(    string path,    Encodingencoding);publicStreamReaderOpenTextFile(    string path);Call primary with default values
Optional and Named ParametersOptional parameterspublicStreamReaderOpenTextFile(    string path,    Encodingencoding,booldetectEncoding,intbufferSize);publicStreamReaderOpenTextFile(    string path,    Encodingencoding = null,booldetectEncoding = true,intbufferSize = 1024);Named argumentOpenTextFile("foo.txt", Encoding.UTF8);OpenTextFile("foo.txt", Encoding.UTF8, bufferSize: 4096);Arguments evaluated in order writtenNamed arguments can appear in any orderNamed arguments must be lastOpenTextFile(bufferSize: 4096,    path: "foo.txt",detectEncoding: false);Non-optional must be specified
Improved COM InteroperabilityobjectfileName = "Test.docx";object missing  = System.Reflection.Missing.Value;doc.SaveAs(reffileName,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");
Automatic object  dynamic mappingOptional and named parametersIndexed propertiesOptional “ref” modifierInterop type embedding (“No PIA”)Improved COM Interoperability
Improved COM Interoperabilitydemo
Co- and Contra-variance.NET arrays are co-variantstring[] strings = GetStringArray();Process(strings);…but not safelyco-variantvoid Process(object[] objects) { … }void Process(object[] objects) {   objects[0] = "Hello";       // Ok   objects[1] = newButton();  // Exception!}Until now, C# generics have been invariantList<string> strings = GetStringList();Process(strings);C# 4.0 supports safe co- and contra-variancevoid Process(IEnumerable<object> objects) { … }void Process(IEnumerable<object> objects) {// IEnumerable<T> is read-only and// therefore safely co-variant}
Safe Co- and Contra-variancepublicinterfaceIEnumerable<T>{IEnumerator<T> GetEnumerator();}publicinterfaceIEnumerable<out T>{IEnumerator<T> GetEnumerator();}out= Co-variantOutput positions onlyCan be treated asless derivedpublicinterfaceIEnumerator<T>{   T Current { get; }boolMoveNext();}publicinterfaceIEnumerator<out T>{   T Current { get; }boolMoveNext();}IEnumerable<string> strings = GetStrings();IEnumerable<object> objects = strings;in= Contra-variantInput positions onlypublicinterfaceIComparer<T>{int Compare(T x, T y);}publicinterfaceIComparer<in T>{int Compare(T x, T y);}Can be treated asmore derivedIComparer<object> objComp = GetComparer();IComparer<string> strComp = objComp;
Variance in C# 4.0Supported for interface and delegate types“Statically checked definition-site variance”Value types are always invariantIEnumerable<int> is not IEnumerable<object>Similar to existing rules for arraysref and out parameters need invariant type
Variance in .NET Framework 4.0InterfacesSystem.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>DelegatesSystem.Func<in T, …, out R>System.Action<in T, …>System.Predicate<in T>System.Comparison<in T>System.EventHandler<in T>
The Evolution of C#C# 4.0Dynamic ProgrammingC# 3.0Language Integrated QueryC# 2.0GenericsC# 1.0Managed Code
Compiler as a ServiceClassMeta-programmingRead-Eval-Print LooppublicFooFieldLanguageObject ModelDSL EmbeddingprivateXstringCompilerCompilerSourceFile.NET AssemblySource codeSource codeSource codeSource code
Compiler as a Servicedemo
Book SigningBookstoreMonday3:30 PM
Related SessionsTL10: Deep Dive: Dynamic Languages in .NETTL54: Natural Interop with Silverlight, Office, …TL12: Future Directions for Microsoft Visual BasicTL57: Panel: The Future of Programming LanguagesTL11: An Introduction to Microsoft F#C# 4.0 Samples and Whitepaperhttp://code.msdn.microsoft.com/csharpfutureVisual C# Developer Centerhttp://csharp.netAdditional Resources
Evals & RecordingsPlease fill out your evaluation for this session at:This session will be available as a recording at:www.microsoftpdc.com
Please use the microphones providedQ&A
© 2008 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.

PDC Video on C# 4.0 Futures

  • 1.
    The Future ofC#TL16 Anders Hejlsberg Technical Fellow Microsoft Corporation
  • 2.
    The Evolution ofC#C# 3.0Language Integrated QueryC# 2.0GenericsC# 1.0Managed Code
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
    The Evolution ofC#C# 4.0Dynamic ProgrammingC# 3.0Language Integrated QueryC# 2.0GenericsC# 1.0Managed Code
  • 9.
    Dynamically Typed ObjectsOptionaland Named ParametersImproved COM InteroperabilityCo- and Contra-varianceC# 4.0 Language Innovations
  • 10.
    .NET Dynamic ProgrammingIronPythonIronRubyC#VB.NETOthers…DynamicLanguage RuntimeExpression TreesDynamic DispatchCall Site CachingPythonBinderRubyBinderCOMBinderJavaScriptBinderObjectBinder
  • 11.
    Dynamically Typed ObjectsCalculatorcalc = GetCalculator();int sum = calc.Add(10, 20);object calc = GetCalculator();TypecalcType = calc.GetType();object res = calcType.InvokeMember("Add",BindingFlags.InvokeMethod, null,newobject[] { 10, 20 });int sum = Convert.ToInt32(res);ScriptObject calc = GetCalculator();object res = calc.Invoke("Add", 10, 20);int sum = Convert.ToInt32(res);Statically typed to be dynamicdynamic calc = GetCalculator();int sum = calc.Add(10, 20);Dynamic method invocationDynamic conversion
  • 12.
    Dynamically Typed ObjectsCompile-timetypedynamicRun-time typeSystem.Int32dynamic x = 1;dynamic y = "Hello";dynamic z = newList<int> { 1, 2, 3 };When operand(s) are dynamic… Member selection deferred to run-time
  • 13.
    At run-time,actual type(s) substituted for dynamic
  • 14.
    Static resulttype of operation is dynamicpublic static class Math{ publicstaticdecimal Abs(decimal value); publicstaticdouble Abs(double value); publicstaticfloat Abs(float value); publicstaticint Abs(int value); publicstaticlong Abs(long value); publicstaticsbyte Abs(sbyte value); publicstaticshort Abs(short value); ...}double x = 1.75;double y = Math.Abs(x);dynamic x = 1.75;dynamic y = Math.Abs(x);Dynamically Typed ObjectsMethod 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)dynamic x = 2;dynamic y = Math.Abs(x);
  • 15.
  • 16.
    IDynamicObjectpublicabstractclassDynamicObject : IDynamicObject{publicvirtualobjectGetMember(GetMemberBinderinfo);publicvirtualobjectSetMember(SetMemberBinder info, object value);publicvirtualobjectDeleteMember(DeleteMemberBinder info); publicvirtualobjectUnaryOperation(UnaryOperationBinder info);publicvirtualobjectBinaryOperation(BinaryOperationBinder info, objectarg);publicvirtualobject Convert(ConvertBinder info); publicvirtualobject Invoke(InvokeBinder info, object[] args);publicvirtualobjectInvokeMember(InvokeMemberBinder info, object[] args);publicvirtualobjectCreateInstance(CreateInstanceBinder info, object[] args); publicvirtualobjectGetIndex(GetIndexBinder info, object[] indices);publicvirtualobjectSetIndex(SetIndexBinder info, object[] indices, object value);publicvirtualobjectDeleteIndex(DeleteIndexBinder info, object[] indices); publicMetaObjectIDynamicObject.GetMetaObject();}
  • 17.
  • 18.
    Optional and NamedParametersPrimary methodpublicStreamReaderOpenTextFile( string path, Encodingencoding,booldetectEncoding,intbufferSize);Secondary overloadspublicStreamReaderOpenTextFile( string path, Encodingencoding,booldetectEncoding);publicStreamReaderOpenTextFile( string path, Encodingencoding);publicStreamReaderOpenTextFile( string path);Call primary with default values
  • 19.
    Optional and NamedParametersOptional parameterspublicStreamReaderOpenTextFile( string path, Encodingencoding,booldetectEncoding,intbufferSize);publicStreamReaderOpenTextFile( string path, Encodingencoding = null,booldetectEncoding = true,intbufferSize = 1024);Named argumentOpenTextFile("foo.txt", Encoding.UTF8);OpenTextFile("foo.txt", Encoding.UTF8, bufferSize: 4096);Arguments evaluated in order writtenNamed arguments can appear in any orderNamed arguments must be lastOpenTextFile(bufferSize: 4096, path: "foo.txt",detectEncoding: false);Non-optional must be specified
  • 20.
    Improved COM InteroperabilityobjectfileName= "Test.docx";object missing = System.Reflection.Missing.Value;doc.SaveAs(reffileName,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");
  • 21.
    Automatic object dynamic mappingOptional and named parametersIndexed propertiesOptional “ref” modifierInterop type embedding (“No PIA”)Improved COM Interoperability
  • 22.
  • 23.
    Co- and Contra-variance.NETarrays are co-variantstring[] strings = GetStringArray();Process(strings);…but not safelyco-variantvoid Process(object[] objects) { … }void Process(object[] objects) { objects[0] = "Hello"; // Ok objects[1] = newButton(); // Exception!}Until now, C# generics have been invariantList<string> strings = GetStringList();Process(strings);C# 4.0 supports safe co- and contra-variancevoid Process(IEnumerable<object> objects) { … }void Process(IEnumerable<object> objects) {// IEnumerable<T> is read-only and// therefore safely co-variant}
  • 24.
    Safe Co- andContra-variancepublicinterfaceIEnumerable<T>{IEnumerator<T> GetEnumerator();}publicinterfaceIEnumerable<out T>{IEnumerator<T> GetEnumerator();}out= Co-variantOutput positions onlyCan be treated asless derivedpublicinterfaceIEnumerator<T>{ T Current { get; }boolMoveNext();}publicinterfaceIEnumerator<out T>{ T Current { get; }boolMoveNext();}IEnumerable<string> strings = GetStrings();IEnumerable<object> objects = strings;in= Contra-variantInput positions onlypublicinterfaceIComparer<T>{int Compare(T x, T y);}publicinterfaceIComparer<in T>{int Compare(T x, T y);}Can be treated asmore derivedIComparer<object> objComp = GetComparer();IComparer<string> strComp = objComp;
  • 25.
    Variance in C#4.0Supported for interface and delegate types“Statically checked definition-site variance”Value types are always invariantIEnumerable<int> is not IEnumerable<object>Similar to existing rules for arraysref and out parameters need invariant type
  • 26.
    Variance in .NETFramework 4.0InterfacesSystem.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>DelegatesSystem.Func<in T, …, out R>System.Action<in T, …>System.Predicate<in T>System.Comparison<in T>System.EventHandler<in T>
  • 27.
    The Evolution ofC#C# 4.0Dynamic ProgrammingC# 3.0Language Integrated QueryC# 2.0GenericsC# 1.0Managed Code
  • 28.
    Compiler as aServiceClassMeta-programmingRead-Eval-Print LooppublicFooFieldLanguageObject ModelDSL EmbeddingprivateXstringCompilerCompilerSourceFile.NET AssemblySource codeSource codeSource codeSource code
  • 29.
    Compiler as aServicedemo
  • 30.
  • 31.
    Related SessionsTL10: DeepDive: Dynamic Languages in .NETTL54: Natural Interop with Silverlight, Office, …TL12: Future Directions for Microsoft Visual BasicTL57: Panel: The Future of Programming LanguagesTL11: An Introduction to Microsoft F#C# 4.0 Samples and Whitepaperhttp://code.msdn.microsoft.com/csharpfutureVisual C# Developer Centerhttp://csharp.netAdditional Resources
  • 32.
    Evals & RecordingsPleasefill out your evaluation for this session at:This session will be available as a recording at:www.microsoftpdc.com
  • 33.
    Please use themicrophones providedQ&A
  • 34.
    © 2008 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.