Dynamic
Hey everyone,
My name is Alex Turner and I'm the Program Manager on the C# Compiler. One of the major language features we're adding in C# 4.0 and VB 10.0 is Dynamic, which provides convenient access to object models that were designed around dynamic dispatch. These object models include the HTML DOM, Python and Ruby libraries, and even COM libraries where the type system often relies on this form of "late binding".
We'd love for you to try this feature out and send us your feedback! There's more information here about the CTP Virtual PC image that contains our preview build of Visual Studio 2010 and a set of walkthroughs you can try, including Dynamic: http://go.microsoft.com/fwlink/?LinkId=129231
Thanks!
Alex
All Replies
- Hi Alex!Dynamic is a nice feature! Do you plan to get invoke a method from a string?And
dynamic myDynamicObject = GetDynamicObject("Person"); will be implemented?Regards!
José Henrique (Zote) - Hi José,
- We have no plans now to accept a method name as a string instead of a token. Did you have a specific scenario in mind?
- It looks like your second example is around creating an object of a dynamic type. We are currently looking into what mechanism we'll use here. In the Silverlight CTP walkthroughs, we work around this issue in the HtmlWindow dynamic binder by providing a convention, win.New.Foo that makes a new object of the JScript type Foo. We may recommend some convention like this to those who create binders or we may look into adding actual support for a dynamic new operator in C#.
Alex
- AlexTurn said:Then it's not really dynamic, since the name is statically fixed at compile time. Why not support true dynamic dispatch?
Hi José,
- We have no plans now to accept a method name as a string instead of a token.
Alex
- We have no plans now to accept a method name as a string instead of a token.
- Hi, Alex.
Would it be possible to use dynamic data type as a type argument?
class A<T>{} ... var x = new A<dynamic>(); // is x of type "A<dynamic>" or "dynamic", or it will raise a compile error?
Update:
More generally what exactly dynamic keyword is? Is it a shortcut for DynamicObject class? Did you have to modify CLR to introduce this dynamic feature? How would compiled code
dynamic str = "test";
look in Reflector?
-Nodir- Edited byNodir Turakulov Thursday, November 06, 2008 10:59 AM
- Al.x said:
Then it's not really dynamic, since the name is statically fixed at compile time. Why not support true dynamic dispatch?
The major scenarios we see for the Dynamic feature involve accessing dynamic object models such as the HTML DOM from Silverlight, and making the calls feel much more natural.
For example, instead of this:
ScriptObject loc = win.CreateInstance("VELatLong", latitude, longitude) ScriptObject pin = (ScriptObject)map.Invoke("AddPushpin", loc); pin.Invoke("SetTitle", title); pin.Invoke("SetDescription", description); map.Invoke("SetCenterAndZoom", loc, 7);
... you can now write this, which has each ScriptObject dynamically dispatch these calls to the JScript engine for you:
dynamic loc = win.New.VELatLong(latitude, longitude) var pin = map.AddPushpin(loc); pin.SetTitle(title); pin.SetDescription(description); map.SetCenterAndZoom(loc, 7);
If your scenario truly does require string-based dynamic dispatch, you can still fall back to the underlying static methods that the object exposes, such as Invoke. - Nodir Turakulov said:
Hi, Alex.
Would it be possible to use dynamic data type as a type argument?
class A<T>{} ... var x = new A<dynamic>(); // is x of type "A<dynamic>" or "dynamic", or it will raise a compile error?
Update:
More generally what exactly dynamic keyword is? Is it a shortcut for DynamicObject class? Did you have to modify CLR to introduce this dynamic feature? How would compiled code
dynamic str = "test";
look in Reflector?
-Nodir
Yup! You can use dynamic in constructed types such as List<dynamic>.
For now, we represent the type dynamic in metadata as System.Object, and then annotate members of type dynamic with [DynamicAttribute]. If a member has a constructed type such as List<dynamic>, we pass a bool array to the [DynamicAttribute] which encodes the exact pieces of the type that are actually dynamic (to distinguish Dictionary<object, dynamic> from Dictionary<dynamic, object>).
For now, this attribute approach hasn't required any changes to the CLR, but we're looking into what the best metadata representation is before we commit to an encoding in this release. - AlexTurn said:Al.x said:
Then it's not really dynamic, since the name is statically fixed at compile time. Why not support true dynamic dispatch?
The major scenarios we see for the Dynamic feature involve accessing dynamic object models such as the HTML DOM from Silverlight, and making the calls feel much more natural.
For example, instead of this:
ScriptObject loc = win.CreateInstance("VELatLong", latitude, longitude) ScriptObject pin = (ScriptObject)map.Invoke("AddPushpin", loc); pin.Invoke("SetTitle", title); pin.Invoke("SetDescription", description); map.Invoke("SetCenterAndZoom", loc, 7);
... you can now write this, which has each ScriptObject dynamically dispatch these calls to the JScript engine for you:
dynamic loc = win.New.VELatLong(latitude, longitude) var pin = map.AddPushpin(loc); pin.SetTitle(title); pin.SetDescription(description); map.SetCenterAndZoom(loc, 7);
If your scenario truly does require string-based dynamic dispatch, you can still fall back to the underlying static methods that the object exposes, such as Invoke.
Different types of dynamic objects have dfferent invoke api, one of the points that Anders mentioned was unifying the dynamic dispatch syntax. If you are going to support dynamic dispatch you should have a single syntax for invoking methods dynamically, .method is not dynamic. It seems you consider dynamic dispacth a hack to ease certain interop scenarios and not a general purpose feature, otherwise implementing a unified trully dynamic invoke would be a no brainer.- Edited byAl.x Thursday, November 06, 2008 8:48 PM
- Could you not simply cast the dynamic type to IDynamic, and call the method-calling method with a string?
- AlexTurn said:Nodir Turakulov said:
Hi, Alex.
Would it be possible to use dynamic data type as a type argument?
class A<T>{} ... var x = new A<dynamic>(); // is x of type "A<dynamic>" or "dynamic", or it will raise a compile error?
Update:
More generally what exactly dynamic keyword is? Is it a shortcut for DynamicObject class? Did you have to modify CLR to introduce this dynamic feature? How would compiled code
dynamic str = "test";
look in Reflector?
-Nodir
Yup! You can use dynamic in constructed types such as List<dynamic>.
For now, we represent the type dynamic in metadata as System.Object, and then annotate members of type dynamic with [DynamicAttribute]. If a member has a constructed type such as List<dynamic>, we pass a bool array to the [DynamicAttribute] which encodes the exact pieces of the type that are actually dynamic (to distinguish Dictionary<object, dynamic> from Dictionary<dynamic, object>).
For now, this attribute approach hasn't required any changes to the CLR, but we're looking into what the best metadata representation is before we commit to an encoding in this release.
So, as I understand the code in C# 4.0
class A { List<dynamic> list; }
is equal to
class A { [DynamicAttribute(new [] {true})] // or smth like this. Sorry I can't download CTP, it is too big List<object> list; }
OK. If it is so, it is clear for me, I understand how you deal with members, but what about variables? You can't define an attribute for a variable. Is code
dynamic str = "sdfsf";
is equal to
?IDynamicObject str = new DynamicObjectWithSimpleObjectBinder("str") // or something like this
And how you deal with variables of constructed types, like List<dynamic>:
void method() { var list = new List<dynamic>(); }
I guess List<dynamic> is not equal to List<IDynamicObject> or List<DynamicObject>. If it would be so, you could you use the same approach in case of members too. So please explain me how do you deal with variables.- Edited byNodir Turakulov Friday, November 07, 2008 7:46 AM
- Al.x said:AlexTurn said:Al.x said:
Then it's not really dynamic, since the name is statically fixed at compile time. Why not support true dynamic dispatch?
The major scenarios we see for the Dynamic feature involve accessing dynamic object models such as the HTML DOM from Silverlight, and making the calls feel much more natural.
For example, instead of this:
ScriptObject loc = win.CreateInstance("VELatLong", latitude, longitude) ScriptObject pin = (ScriptObject)map.Invoke("AddPushpin", loc); pin.Invoke("SetTitle", title); pin.Invoke("SetDescription", description); map.Invoke("SetCenterAndZoom", loc, 7);
... you can now write this, which has each ScriptObject dynamically dispatch these calls to the JScript engine for you:
dynamic loc = win.New.VELatLong(latitude, longitude) var pin = map.AddPushpin(loc); pin.SetTitle(title); pin.SetDescription(description); map.SetCenterAndZoom(loc, 7);
If your scenario truly does require string-based dynamic dispatch, you can still fall back to the underlying static methods that the object exposes, such as Invoke.
Different types of dynamic objects have dfferent invoke api, one of the points that Anders mentioned was unifying the dynamic dispatch syntax. If you are going to support dynamic dispatch you should have a single syntax for invoking methods dynamically, .method is not dynamic. It seems you consider dynamic dispacth a hack to ease certain interop scenarios and not a general purpose feature, otherwise implementing a unified trully dynamic invoke would be a no brainer.
But isn't it strange to ask for "real dynamic" features that popular dynamic languages doesn't provide?
JavaScript for example requires the normal member lookup syntax to have a token to define the member to access, so what follows the "." has to be a single token to designate the name of member instead of an arbitrary string. It does however provide an alternative syntax to access member via string, with square brackets.
obj['foo']() // get member 'foo' from obj and call it
With C# 4.0's dynamic features, the same syntax may work just as well (but dynamic index dispatch isn't implemented in CTP yet).
The dot syntax in Ruby or Python doesn't provide what you'd call "real dynamic" feature neither. Again, they have alternative syntax to access member in a reflection manner, with strings as arguments.
- RednaxelaFX (Kris Mok) - RednaxelaFX said:Al.x said:AlexTurn said:Al.x said:
Then it's not really dynamic, since the name is statically fixed at compile time. Why not support true dynamic dispatch?
The major scenarios we see for the Dynamic feature involve accessing dynamic object models such as the HTML DOM from Silverlight, and making the calls feel much more natural.
For example, instead of this:
ScriptObject loc = win.CreateInstance("VELatLong", latitude, longitude) ScriptObject pin = (ScriptObject)map.Invoke("AddPushpin", loc); pin.Invoke("SetTitle", title); pin.Invoke("SetDescription", description); map.Invoke("SetCenterAndZoom", loc, 7);
... you can now write this, which has each ScriptObject dynamically dispatch these calls to the JScript engine for you:
dynamic loc = win.New.VELatLong(latitude, longitude) var pin = map.AddPushpin(loc); pin.SetTitle(title); pin.SetDescription(description); map.SetCenterAndZoom(loc, 7);
If your scenario truly does require string-based dynamic dispatch, you can still fall back to the underlying static methods that the object exposes, such as Invoke.
Different types of dynamic objects have dfferent invoke api, one of the points that Anders mentioned was unifying the dynamic dispatch syntax. If you are going to support dynamic dispatch you should have a single syntax for invoking methods dynamically, .method is not dynamic. It seems you consider dynamic dispacth a hack to ease certain interop scenarios and not a general purpose feature, otherwise implementing a unified trully dynamic invoke would be a no brainer.
But isn't it strange to ask for "real dynamic" features that popular dynamic languages doesn't provide?
JavaScript for example requires the normal member lookup syntax to have a token to define the member to access, so what follows the "." has to be a single token to designate the name of member instead of an arbitrary string. It does however provide an alternative syntax to access member via string, with square brackets.
obj['foo']() // get member 'foo' from obj and call it
With C# 4.0's dynamic features, the same syntax may work just as well (but dynamic index dispatch isn't implemented in CTP yet).
The dot syntax in Ruby or Python doesn't provide what you'd call "real dynamic" feature neither. Again, they have alternative syntax to access member in a reflection manner, with strings as arguments.
- RednaxelaFX (Kris Mok)
As you pojnted out yourself JS has the obj[string_expression]() syntax; also the call and apply methods on functions. Perhaps the poster that brought up this issue had in mind particular syntax (obj.string_expression()) but all I am saying is there should be A staright forward and generic way to invoke a method by name on a dynamic object.
So far the official word from the compiler PM is there won't be one. This is the only non generic alternative he mentioned:
"you can still fall back to the underlying static methods that the object exposes, such as Invoke." - @AI.x
With regards to this sentence:
>> We have no plans now to accept a method name as a string instead of a token.
My take is that this is just talking about the dot syntax for member lookup. There may still be room for other solutions than invoking the uderlying static methods.
With DLR as the underlying platform, I don't see why the JavaScript style of member lookup via indexer won't work in C# 4. It already works in Managed JScript, and the mechanism is just the same: GetIndex, then Invoke. The normal dot syntax might be translated into a InvokeMember, but obj['foo']() can only translated as GetIndex + Invoke. I guess...
If the dynamic object you have is a "smart guy" (implements IDynamicObject, and implements dynamic indexer), then C# 4 will have no problem invoking the member you got back from the indexer, as long as it supports invoke (say it's a delegate, or another "smart guy" that supports Invoke). In fact C# 4 has no control of what the dynamic object will do if the object is smart enough.
On the other hand, if the object is not "smart" enough (might be a plain old static CLR object), DLR's dynamic dispatch falls back to C# 4's runtime binder. This is where C# 4 gains control over the object's behavior. Because C# 4's dynamic indexer isn't implemented in the CTP yet, there's little we can tell about how it's going to behave. Hopefully they will come up with something useful. But I can see issues around using indexer as a means of reflection in C# 4's dynamic feature, because a lot of plain old CLR object already have indexers that take a string as an argument, can't just "override" those...well, I don't know. I want that "straight forward and generic way to invoke a method by name on a dynamic object" just as you do. Often times it's exactly because I can't get the name of the method ahead of time that I had to use reflection.
- RednaxelaFX (Kris Mok) About the issues with dynamic objects and extension methods:
Why not make the compiler capture the 'using' references and scoping context from the compile-time into the special kind of method- or class-level attributes?
That way, we'll seamlessly integrate compile-time scoping and resolution rules with the run-time, with much less hassle to the users, and enabling Reflection support for all the compile-time C# 3.0 and 4.0 features (for example, named parameters in dynamic method calls and so on)
Oh, i mean, i'm referring to the document linked from this post: http://blogs.msdn.com/charlie/archive/2008/11/04/new-features-in-c-4-0-paper-plus-feedback-and-samples.aspx :)- Edited bywizzard0 Thursday, November 13, 2008 3:43 AM
- Will the new dynamic features allow for an eval() style function, as you find in VBA or J#?
Certain user interface problems need eval(), such as ui's that make use of on the fly user-generated functions and equations.
Thanks.
(p.s. hard to use to this webform to post because on my vista pc ie7 cuts off the bottom. ) - Hi Alex - have you posted the version of your CTP Silverlight sample after the changes you made during your talk? Thanks!
- Hello,
I got an idea of possible feature and I am curious about your opinions.
What about to combine lambda expressions and dynamic ... and create object/property
selectors? Like XPath over objects and properties?
Scenario of usage:
A) Want to create collection from object properties
class Employee {
public string Name {
....
}
List<Employee> e;
List<string> names = new List<string>(e, Name);
B) Having some HTML DOM, trying to update in all elements <A>, elements <SPAN> to set property Style.Font.Weight=bold
class HTMLDomDocument {
List<AHtmlElement> links;
}
HTMLDomDocument doc;
foreach(MyCrazySelectedPropertyOrObject p in doc.links->children as SpanHtmlElement->Style->Font->Weight){
p = "bold";
}
C) COM & Excel? perhaps
ExcelWorkSheet ews;
foreach(MyCrazySelectedPropertyOrObject p in ews->Sheets->Cells[0..3][0..5] -> Value)
{
p = "These are the cells in first three columns and first five rows";
}
D) Just crazy, sure not motivating to use it this way :)
class Magic {
public string A {
...
};
public string B {
....
}
private MyCrazySelectedPropertyOrObject x;
string X {
get {
return x;
}
set {
x = value; //setting string to underlying property
if(x.BindsTo(this.A))
x = this->B; else x = this->A;
}
public Magic()
{
x = this->A;
}
}
Magic foo = new Magic();
foo.X = "A";
foo.X = "B";
Console.WriteLine(foo.A); //"A"
Console.WriteLine(foo.B); //"B"
foo.X = "B";
Console.WriteLine(foo.A); //"B"
------
Sure, it may appear mostly as non-sense examples, esp. the imaginary syntax is more than confusing but I hope
I managed to point the idea.
It would work also like CSS selectors, but more generally of course. - Do I need to use MetaObject all the time, to implement IDynamicObject? Or some wrappers will be exist?
Will there be any *hacks* for DLR? or DLR-based languages and non-DLR will be work (can use IDynamicObject) equally? - A couple of questions.
In the CTP bits, some things I tried don't work. d + 5 where 'd' is dynamic gives me a compiler error, and I've seen blog posts that indicate that will be supported. But what about events:d.Click += delegate { ... }
Will the += operator be usable on event-like fields like the above as a way to enlist (along with -= obviously)?
Also I have a question about extension methods. I appreciate that some things probably wont work, e.g.dynamic d = new List<int> {1, 2, 3}; dynamic even = d.Where(n => (n % 2 == 0));
The call to Where would have to be resolved at runtime, which would mean searching through all available types at runtime and somehow knowing what using directives had been put in the source... sounds a little unpredictable.
But what about defining an extension method on the dynamic type itself?public static T As<T>(this dynamic o)
The compiler doesn't pick that up either, even though it's resolvable purely at compile time - it would be handy as a way to provide utilities for working with dynamic references.
- Didn't see a reply on this (perhaps related to "call method as string" request above):
Would like to see an eval() style function, as you find in VBA or the old J#.
Certain user interface problems need eval(), such as painlessly mixing in on the fly user-created custom functions or expressions into a program.
Thanks.

