Required Slide<br />Introduction to C# 4.0 and Dynamic<br />By: Gieno Miao<br />gieno.miao@live.com<br />
The Evolution of C#<br />C# 4.0<br />Dynamic Programming<br />C# 3.0<br />Language Integrated Query<br />Ruby On Rails 2.0...
C# 4.0 Language Innovations<br />Dynamically Typed Objects<br />Optional and Named Parameters<br />Improved COM Interopera...
Why Dynamic?<br />There is a lot of interest in accessing the highly dynamic object model of HTML DOM<br />COM is heavily ...
.NET Dynamic Programming Architecture<br />IronPython<br />IronRuby<br />C#<br />VB.NET<br />Others…<br />Dynamic Language...
Dynamically Typed Objects<br />Calculator calc = GetCalculator();<br />int sum = calc.Add(10, 20);<br />.NET object<br />o...
dynamic calc = GetCalculator();<br />int sum = calc.Add(10, 20);<br />Under the cover<br />dynamic is a new type only in t...
dynamici = 3;<br />Math.Abs(i);<br />Under the cover<br />For binding calls to .NET types there is a runtime C# binder<br ...
Under the cover<br />When dose the compiler dispatch dynamically?<br />if the receiver of the call is dynamic OR<br />if a...
Under the cover<br />dynamic d = newDynamicObject();<br />d.Foo();<br />You can now write your own object that does dynami...
IDynamicObject<br />publicabstractclassDynamicObject : IDynamicObject<br />{<br />publicvirtualobjectGetMember(GetMemberBi...
Improved COM interoperability<br />Automatic object -> dynamic mapping<br />Optional and named parameters<br />Optional “r...
object -> dynamic mapping<br />We need to cast<br />((Excel.Range)xl.Cells[1,1]).Value2 = “ID”;<br />xl.Cells[1,1].Value2 ...
Optional and named parameters<br />xlChart.ChartWizard(cellRange.CurrentRegion,<br />    Constants.xl3DBar, Type.Missing, ...
Optional and named parameters<br />Optional parameters<br />publicStreamReaderOpenTextFile(<br />    string path,<br />   ...
Optional “ref” modifier<br />objectfileName = "Test.docx";<br />object missing  = System.Reflection.Missing.Value;<br />do...
Under the cover<br />The default value for a parameter is encoded with DefaultParameterValue attribute<br />The compiler i...
Under the cover<br />You can override methods that declare optional parameters<br />The value of the parameter comes from ...
Co- and Contra-variance<br />.NET arrays are co-variant<br />string[] strings = GetStringArray();<br />Process(strings);<b...
Safe Co- and Contra-variance<br />publicinterfaceIEnumerable<T><br />{<br />IEnumerator<T> GetEnumerator();<br />}<br />pu...
Variance in C# 4.0<br />supported for interface and delegate types<br />statically checked definition site variance<br />v...
Summary<br />We have a new type called dynamic<br />Calls that involve variables of type dynamic are treated differently b...
How dynamic works<br />CLR<br />Expression Tree<br />COM Binder<br />Exe<br />IronPython Binder<br />Compile<br />Run<br /...
Review<br />What is the dynamic type?<br />There is no dynamic type . There is only object.<br />What operations are supp...
What does a CallSite contain?<br />Information about the call being made<br />What type of call (method call, property acc...
Dynamic FAQ<br />When do you go dynamic?<br />When the target of the call OR any of the call arguments are dynamic<br />Wh...
Dynamic FAQ<br />What about private methods?<br />Information about the context of call is embedded in the CallSite allowi...
Dynamic FAQ<br />Can I use named and optional with dynamic?<br />Yes <br />And also Co & Contra variance<br />Where can’t...
 Quiz!<br />classBase {<br />    publicvirtualvoid Foo(int x = 4, int y = 5) {<br />        Console.WriteLine("x:{0}, y:{...
Introduction to c sharp 4.0 and dynamic
Upcoming SlideShare
Loading in …5
×

Introduction to c sharp 4.0 and dynamic

2,159 views

Published on

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

  • Be the first to like this

No Downloads
Views
Total views
2,159
On SlideShare
0
From Embeds
0
Number of Embeds
136
Actions
Shares
0
Downloads
51
Comments
0
Likes
0
Embeds 0
No embeds

No notes for slide

Introduction to c sharp 4.0 and dynamic

  1. 1. Required Slide<br />Introduction to C# 4.0 and Dynamic<br />By: Gieno Miao<br />gieno.miao@live.com<br />
  2. 2. The Evolution of C#<br />C# 4.0<br />Dynamic Programming<br />C# 3.0<br />Language Integrated Query<br />Ruby On Rails 2.0<br />C# 2.0<br />Generics<br />Java EE 5, Ruby On Rails 1.0<br />C# 1.0<br />Managed Code<br />Mono announced, J2SE 1.4<br />
  3. 3. C# 4.0 Language Innovations<br />Dynamically Typed Objects<br />Optional and Named Parameters<br />Improved COM Interoperability<br />Co- and Contra-variance<br />
  4. 4. Why Dynamic?<br />There is a lot of interest in accessing the highly dynamic object model of HTML DOM<br />COM is heavily used and inter op code could be easier to read and write<br />Dynamic languages are becoming increasingly popular<br /> We need unified way to work with all of the above<br />
  5. 5. .NET Dynamic Programming Architecture<br />IronPython<br />IronRuby<br />C#<br />VB.NET<br />Others…<br />Dynamic Language Runtime<br />Expression Trees<br />Dynamic Dispatch<br />Call Site Caching<br />PythonBinder<br />RubyBinder<br />COMBinder<br />JavaScriptBinder<br />ObjectBinder<br />
  6. 6. Dynamically Typed Objects<br />Calculator calc = GetCalculator();<br />int sum = calc.Add(10, 20);<br />.NET object<br />object calc = GetCalculator();<br />TypecalcType = calc.GetType();<br />object res = calcType.InvokeMember("Add",<br />BindingFlags.InvokeMethod, null,<br />newobject[] { 10, 20 });<br />int sum = Convert.ToInt32(res);<br />Dynamic Language object<br />ScriptObject calc = GetCalculator();<br />object res = calc.Invoke("Add", 10, 20);<br />int sum = Convert.ToInt32(res);<br />Statically typed to be dynamic<br />dynamic calc = GetCalculator();<br />int sum = calc.Add(10, 20);<br />Dynamic method invocation<br />Dynamic conversion<br />
  7. 7. dynamic calc = GetCalculator();<br />int sum = calc.Add(10, 20);<br />Under the cover<br />dynamic is a new type only in the compiler<br />Encoded in IL as object + dynamic attribute<br />Operations on a dynamic variable become CallSites, objects “interpreted” by the DLR<br />member selection deferred to run-time<br />cache the result of the bindings<br />the return type of a dynamic operation is dynamic<br />Support all types of operations on dynamic<br />method call, property access, indexer access, operators, conversions<br />
  8. 8. dynamici = 3;<br />Math.Abs(i);<br />Under the cover<br />For binding calls to .NET types there is a runtime C# binder<br />Does overload resolution using runtime types for dynamic arguments<br />Overload resolution changed to accommodate dynamic method calls<br />Dynamic arguments are treated as wildcards for overload resolution<br />
  9. 9. Under the cover<br />When dose the compiler dispatch dynamically?<br />if the receiver of the call is dynamic OR<br />if any of the arguments to the call are typed dynamic<br />We can dynamically dispatch to static methods <br />
  10. 10. Under the cover<br />dynamic d = newDynamicObject();<br />d.Foo();<br />You can now write your own object that does dynamic dispatch<br />just implement IDynamicObject<br />The C# runtime binder can function as a fallback for calls to dynamic objects<br />if your object is “hybrid” and some of the methods are dynamically dispatched and some are regular methods<br />the C# semantics will be applied if the Object cannot itself resolve a call<br />
  11. 11. IDynamicObject<br />publicabstractclassDynamicObject : IDynamicObject<br />{<br />publicvirtualobjectGetMember(GetMemberBinder info);<br />publicvirtualobjectSetMember(SetMemberBinder info, object value);<br />publicvirtualobjectDeleteMember(DeleteMemberBinder info);<br /> <br />publicvirtualobjectUnaryOperation(UnaryOperationBinder info);<br />publicvirtualobjectBinaryOperation(BinaryOperationBinder info, objectarg);<br />publicvirtualobject Convert(ConvertBinder info);<br /> <br />publicvirtualobject Invoke(InvokeBinder info, object[] args);<br />publicvirtualobjectInvokeMember(InvokeMemberBinder info, object[] args);<br />publicvirtualobjectCreateInstance(CreateInstanceBinder info, object[] args);<br /> <br />publicvirtualobjectGetIndex(GetIndexBinder info, object[] indices);<br />publicvirtualobjectSetIndex(SetIndexBinder info, object[] indices, object value);<br />publicvirtualobjectDeleteIndex(DeleteIndexBinder info, object[] indices);<br /> <br />publicMetaObjectIDynamicObject.GetMetaObject();<br />}<br />
  12. 12. Improved COM interoperability<br />Automatic object -> dynamic mapping<br />Optional and named parameters<br />Optional “ref” modifier<br />Interop type embedding (“No PIA”)<br />Indexed properties<br />
  13. 13. object -> dynamic mapping<br />We need to cast<br />((Excel.Range)xl.Cells[1,1]).Value2 = “ID”;<br />xl.Cells[1,1].Value2 = “ID”;<br />When the return type of a COM call is object you are forced to cast to a known type<br />Making the code harder to understand<br />If the return type is dynamic, you can continue to “dot” on the return type<br />If you typed something wrong the compiler won’t tell you<br />
  14. 14. Optional and named parameters<br />xlChart.ChartWizard(cellRange.CurrentRegion,<br />    Constants.xl3DBar, Type.Missing, Excel.XlRowCol.xlColumns,<br /> 1, 2, false, xlSheet.Name, Type.Missing, <br />Type.Missing, Type.Missing);<br />Non-optional must be specified<br />xlChart.ChartWizard(cellRange.CurrentRegion, Constants.xl3DBar, <br />PlotBy: Excel.XlRowCol.xlColumns,<br />SeriesLabels: 2, <br />CategoryLabels: 1, <br />HasLegend: false,<br /> Title: xlSheet.Name);<br />Arguments evaluated in order written<br />Named arguments can appear in any order<br />
  15. 15. Optional and named parameters<br />Optional parameters<br />publicStreamReaderOpenTextFile(<br /> string path,<br /> Encodingencoding,<br />booldetectEncoding,<br />intbufferSize);<br />publicStreamReaderOpenTextFile(<br /> string path,<br /> Encodingencoding = null,<br />booldetectEncoding = true,<br />intbufferSize = 1024);<br />Named argument<br />OpenTextFile("foo.txt”);<br />OpenTextFile("foo.txt", Encoding.UTF8, bufferSize: 4096);<br />
  16. 16. Optional “ref” modifier<br />objectfileName = "Test.docx";<br />object missing = System.Reflection.Missing.Value;<br />doc.SaveAs(reffileName,<br />ref missing, ref missing, ref missing,<br />ref missing, ref missing, ref missing,<br />ref missing, ref missing, ref missing,<br />ref missing, ref missing, ref missing,<br />ref missing, ref missing, ref missing);<br />doc.SaveAs("Test.docx");<br />
  17. 17. Under the cover<br />The default value for a parameter is encoded with DefaultParameterValue attribute<br />The compiler inserts that value if a value is not specified for that parameter<br />If a default value is not specified we will use default (type)<br />For COM the compiler will pass in Type.Missing<br />The compiler will rearrange the specified named parameters and then apply overload resolution<br />
  18. 18. Under the cover<br />You can override methods that declare optional parameters<br />The value of the parameter comes from the static type you used to call the method<br />You can rename a parameter in an override<br />The compiler will use the name found in the static type you used to call the method<br />“Omit ref” only works for COM objects<br />The compiler creates a variable to store the value you specified and passes the created variable “by ref” to COM<br />
  19. 19. Co- and Contra-variance<br />.NET arrays are co-variant<br />string[] strings = GetStringArray();<br />Process(strings);<br />…but not safelyco-variant<br />void Process(object[] objects) { … }<br />void Process(object[] objects) {<br /> objects[0] = "Hello"; // Ok<br /> objects[1] = newButton(); // Exception!<br />}<br />Until now, C# generics have been invariant<br />List<string> strings = GetStringList();<br />Process(strings);<br />C# 4.0 supports safe co- and contra-variance<br />void Process(IEnumerable<object> objects) { … }<br />void Process(IEnumerable<object> objects) {<br />// IEnumerable<T> is read-only and<br />// therefore safely co-variant<br />}<br />
  20. 20. Safe Co- and Contra-variance<br />publicinterfaceIEnumerable<T><br />{<br />IEnumerator<T> GetEnumerator();<br />}<br />publicinterfaceIEnumerable<out T><br />{<br />IEnumerator<T> GetEnumerator();<br />}<br />out= Co-variantOutput positions only<br />Can be treated asless derived<br />publicinterfaceIEnumerator<T><br />{<br /> T Current { get; }<br />boolMoveNext();<br />}<br />publicinterfaceIEnumerator<out T><br />{<br /> T Current { get; }<br />boolMoveNext();<br />}<br />IEnumerable<string> strings = GetStrings();<br />IEnumerable<object> objects = strings;<br />in= Contra-variantInput positions only<br />publicinterfaceIComparer<T><br />{<br />int Compare(T x, T y);<br />}<br />publicinterfaceIComparer<in T><br />{<br />int Compare(T x, T y);<br />}<br />Can be treated asmore derived<br />IComparer<object> objComp = GetComparer();<br />IComparer<string> strComp = objComp;<br />
  21. 21. Variance in C# 4.0<br />supported for interface and delegate types<br />statically checked definition site variance<br />value types are always invariant<br />IEnumerable<int> is not IEnumerable<object><br />similar to existing rules for arrays<br />ref and out parameters need invariant type<br />
  22. 22. Summary<br />We have a new type called dynamic<br />Calls that involve variables of type dynamic are treated differently by compiler<br />We package extra information about the call<br />Calls can be: method calls, property access, indexer call, operator call<br />There is a C# runtime binder to interpret the information (at runtime)<br />It uses the runtime type for all dynamic arguments<br />It uses the compile time type for all other arguments<br />
  23. 23. How dynamic works<br />CLR<br />Expression Tree<br />COM Binder<br />Exe<br />IronPython Binder<br />Compile<br />Run<br />Bind call<br />Dynamic Call<br />Delegate<br />DLR<br />C# Runtime Binder<br />Cache<br />…<br />
  24. 24. Review<br />What is the dynamic type?<br />There is no dynamic type . There is only object.<br />What operations are supported?<br />A variable of type dynamic is assumed to support any kind of operation (method call, property access, indexer call and operator call)<br />How is the information about the call stored?<br />Using CallSites objects the compiler packages data about the call<br />
  25. 25. What does a CallSite contain?<br />Information about the call being made<br />What type of call (method call, property access, etc)<br />The name of the member<br />The context of the call<br />The type arguments for the call<br />Information about the parameter and return types<br />Is it a constant? Is it passed by-ref, etc.<br />
  26. 26. Dynamic FAQ<br />When do you go dynamic?<br />When the target of the call OR any of the call arguments are dynamic<br />What is the return type of a dynamic call?<br />It is dynamic in most case<br />What about conversions and constructors?<br />They are dispatched at runtime, but their return type is known at compile time<br />
  27. 27. Dynamic FAQ<br />What about private methods?<br />Information about the context of call is embedded in the CallSite allowing the Binder to “do the right thing”<br />Calling a method off a non-dynamic target with dynamic arguments<br />It works as expected <br />We embed the type of all the receiver in the CallSite<br />Can dynamic “cross” assembly boundaries?<br />Yes, we decorate any dynamic parameter or return type with a DynamicAttribute<br />It works for generic types constructed with dynamic as well <br />
  28. 28. Dynamic FAQ<br />Can I use named and optional with dynamic?<br />Yes <br />And also Co & Contra variance<br />Where can’t I use dynamic?<br />Lambda expressions<br />LINQ<br />Can’t use dynamic with method groups<br />Throw or catch statements<br />
  29. 29.  Quiz!<br />classBase {<br />    publicvirtualvoid Foo(int x = 4, int y = 5) {<br />        Console.WriteLine("x:{0}, y:{1}", x, y);<br />    }<br />}<br />classDerived : Base {<br />    publicoverridevoid Foo(int y = 4, int x = 5) {<br />        Console.WriteLine("x:{0}, y:{1}", x, y);<br />    }<br />}<br />classProgram {<br />    staticvoid Main(string[] args) {<br />        Base b = newDerived();<br />        b.Foo(x: 4, y: 5);<br />    }<br />}<br />Output:<br />x:4, y:5<br />x:5, y:4<br />x:4, y:4<br />x:5, y:5<br />None of the above<br />Output:<br />x:4, y:5<br />x:5, y:4<br />x:4, y:4<br />x:5, y:5<br />None of the above<br />

×