Introduction to c sharp 4.0 and dynamic

download Introduction to c sharp 4.0 and dynamic

If you can't read please download the document

Transcript of Introduction to c sharp 4.0 and dynamic

Programming Tips and Tricks - Data Access Best Practices

By: Gieno [email protected] SlideIntroduction to C# 4.0 and Dynamic

1

Tech Ed North America 20102010810210 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.

C# 1.0C# 2.0C# 3.0Managed CodeMono announced, J2SE 1.4GenericsJava EE 5, Ruby On Rails 1.0Language Integrated QueryRuby On Rails 2.0

C# 4.0Dynamic ProgrammingThe Evolution of C#

NOTE The pioneering role of Microsoft ResearchMicrosoft Research is responsible for some of the new directions for .NET and C#. They published a paper on .NET generics as early as May 2001 (yes, even before .NET 1.0 had been released!) and worked on an extension called C (pronounced C omega), which includedamong other thingssome of the ideas which later formed LINQ. Another C# extension, Spec#, adds contracts to C#, allowing the compiler to do more verification automatically.6 We will have to wait and see whether any or all of the ideas of Spec# eventually become part of C# itself.

C# 4.0 Language InnovationsDynamically Typed ObjectsOptional and Named ParametersImproved COM InteroperabilityCo- and Contra-variance

Why Dynamic?There is a lot of interest in accessing the highly dynamic object model of HTML DOMCOM is heavily used and inter op code could be easier to read and writeDynamic languages are becoming increasingly popular

We need unified way to work with all of the above

PythonBinderRubyBinderCOMBinderJavaScriptBinderObjectBinder

Dynamic Language RuntimeExpression TreesDynamic DispatchCall Site CachingIronPythonIronRubyC#VB.NETOthers

.NET Dynamic Programming Architecture

5

.NET objectobject calc = GetCalculator();Type calcType = calc.GetType();object res = calcType.InvokeMember("Add", BindingFlags.InvokeMethod, null, new object[] { 10, 20 });int sum = Convert.ToInt32(res);Dynamic Language objectScriptObject calc = GetCalculator();object res = calc.Invoke("Add", 10, 20);int sum = Convert.ToInt32(res);Calculator calc = GetCalculator();int sum = calc.Add(10, 20);dynamic calc = GetCalculator();int sum = calc.Add(10, 20);Statically typed to be dynamicDynamic method invocationDynamic conversionDynamically Typed Objects

Under the coverdynamic is a new type only in the compilerEncoded in IL as object + dynamic attribute

Operations on a dynamic variable become CallSites, objects interpreted by the DLRmember selection deferred to run-timecache the result of the bindingsthe return type of a dynamic operation is dynamic

Support all types of operations on dynamicmethod call, property access, indexer access, operators, conversionsdynamic calc = GetCalculator();int sum = calc.Add(10, 20);

Under the coverFor binding calls to .NET types there is a runtime C# binderDoes overload resolution using runtime types for dynamic arguments

Overload resolution changed to accommodate dynamic method callsDynamic arguments are treated as wildcards for overload resolutiondynamic i = 3;Math.Abs(i);

Under the coverWhen dose the compiler dispatch dynamically?if the receiver of the call is dynamic ORif any of the arguments to the call are typed dynamic

We can dynamically dispatch to static methods

Under the coverYou can now write your own object that does dynamic dispatchjust implement IDynamicObject

The C# runtime binder can function as a fallback for calls to dynamic objectsif your object is hybrid and some of the methods are dynamically dispatched and some are regular methodsthe C# semantics will be applied if the Object cannot itself resolve a calldynamic d = new DynamicObject();d.Foo();

public abstract class DynamicObject : IDynamicObject{ public virtual object GetMember(GetMemberBinder info); public virtual object SetMember(SetMemberBinder info, object value); public virtual object DeleteMember(DeleteMemberBinder info); public virtual object UnaryOperation(UnaryOperationBinder info); public virtual object BinaryOperation(BinaryOperationBinder info, object arg); public virtual object Convert(ConvertBinder info); public virtual object Invoke(InvokeBinder info, object[] args); public virtual object InvokeMember(InvokeMemberBinder info, object[] args); public virtual object CreateInstance(CreateInstanceBinder info, object[] args); public virtual object GetIndex(GetIndexBinder info, object[] indices); public virtual object SetIndex(SetIndexBinder info, object[] indices, object value); public virtual object DeleteIndex(DeleteIndexBinder info, object[] indices); public MetaObject IDynamicObject.GetMetaObject();}IDynamicObject

11

Improved COM interoperabilityAutomatic object dynamic mappingOptional and named parametersOptional ref modifierInterop type embedding (No PIA)Indexed properties

object -> dynamic mappingWhen the return type of a COM call is object you are forced to cast to a known typeMaking the code harder to understandIf the return type is dynamic, you can continue to dot on the return typeIf you typed something wrong the compiler wont tell you((Excel.Range)xl.Cells[1,1]).Value2 = ID;We need to castxl.Cells[1,1].Value2 = ID;

xlChart.ChartWizard(cellRange.CurrentRegion, Constants.xl3DBar, PlotBy: Excel.XlRowCol.xlColumns, SeriesLabels: 2, CategoryLabels: 1, HasLegend: false, Title: xlSheet.Name);Non-optional must be specifiedArguments evaluated in order writtenNamed arguments can appear in any orderxlChart.ChartWizard(cellRange.CurrentRegion, Constants.xl3DBar, Type.Missing, Excel.XlRowCol.xlColumns, 1, 2, false, xlSheet.Name, Type.Missing, Type.Missing, Type.Missing);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 parametersOpenTextFile("foo.txt);OpenTextFile("foo.txt", Encoding.UTF8, bufferSize: 4096);Named argument

Optional and named parameters

15

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");Optional ref modifier

Under the coverThe default value for a parameter is encoded with DefaultParameterValue attributeThe compiler inserts that value if a value is not specified for that parameterIf a default value is not specified we will use default (type)For COM the compiler will pass in Type.MissingThe compiler will rearrange the specified named parameters and then apply overload resolution

Under the coverYou can override methods that declare optional parametersThe value of the parameter comes from the static type you used to call the methodYou can rename a parameter in an overrideThe compiler will use the name found in the static type you used to call the methodOmit ref only works for COM objectsThe compiler creates a variable to store the value you specified and passes the created variable by ref to COM

void Process(object[] objects) { }string[] strings = GetStringArray();Process(strings);void Process(object[] objects) { objects[0] = "Hello"; // Ok objects[1] = new Button(); // Exception!}List strings = GetStringList();Process(strings);void Process(IEnumerable objects) { }.NET arrays are co-variantbut not safelyco-variantUntil now, C# generics have been invariantvoid Process(IEnumerable objects) { // IEnumerable is read-only and // therefore safely co-variant}

C# 4.0 supports safe co- and contra-varianceCo- and Contra-variance

19

public interface IEnumerable{ IEnumerator GetEnumerator();}public interface IEnumerator{ T Current { get; } bool MoveNext();}public interface IEnumerable{ IEnumerator GetEnumerator();}public interface IEnumerator{ T Current { get; } bool MoveNext();}out = Co-variantOutput positions only

IEnumerable strings = GetStrings();IEnumerable objects = strings;Can be treated asless derivedpublic interface IComparer{ int Compare(T x, T y);}public interface IComparer{ int Compare(T x, T y);}

IComparer objComp = GetComparer();IComparer strComp = objComp;in = Contra-variantInput positions onlyCan be treated asmore derivedSafe Co- and Contra-variance

20

Variance in C# 4.0supported for interface and delegate typesstatically checked definition site variancevalue types are always invariantIEnumerable is not IEnumerablesimilar to existing rules for arraysref and out parameters need invariant type

SummaryWe have a new type called dynamicCalls that involve variables of type dynamic are treated differently by compilerWe package extra information about the callCalls can be: method calls, property access, indexer call, operator callThere is a C# runtime binder to interpret the information (at runtime)It uses the runtime type for all dynamic argumentsIt uses the compile time type for all other arguments

CLR

ExeCompileRunBind callExpression Tree

Dynamic CallDelegate

DLRCacheCOM BinderIronPython BinderC# Runtime BinderHow dynamic works

23

ReviewWhat is the dynamic type?There is no dynamic type . There is only object.What operations are supported?A variable of type dynamic is assumed to support any kind of operation (method call, property access, indexer call and operator call)How is the information about the call stored?Using CallSites objects the compiler packages data about the call

What does a CallSite contain?Information about the call being madeWhat type of call (method call, property access, etc)The name of the memberThe context of the callThe type arguments for the callInformation about the parameter and return typesIs it a constant? Is it passed by-ref, etc.

Dynamic FAQWhen do you go dynamic?When the target of the call OR any of the call arguments are dynamicWhat is the return type of a dynamic call?It is dynamic in most caseWhat about conversions and constructors?They are dispatched at runtime, but their return type is known at compile time

Dynamic FAQWhat about private methods?Information about the context of call is embedded in the CallSite allowing the Binder to do the right thingCalling a method off a non-dynamic target with dynamic argumentsIt works as expected We embed the type of all the receiver in the CallSiteCan dynamic cross assembly boundaries?Yes, we decorate any dynamic parameter or return type with a DynamicAttributeIt works for generic types constructed with dynamic as well

Dynamic FAQCan I use named and optional with dynamic?Yes And also Co & Contra varianceWhere cant I use dynamic?Lambda expressionsLINQCant use dynamic with method groupsThrow or catch statements

class Base { public virtual void Foo(int x = 4, int y = 5) { Console.WriteLine("x:{0}, y:{1}", x, y); }}

class Derived : Base { public override void Foo(int y = 4, int x = 5) { Console.WriteLine("x:{0}, y:{1}", x, y); }}

class Program { static void Main(string[] args) { Base b = new Derived(); b.Foo(x: 4, y: 5); }}Output:x:4, y:5x:5, y:4x:4, y:4x:5, y:5None of the aboveOutput:x:4, y:5x:5, y:4x:4, y:4x:5, y:5None of the above Quiz!

30