views:

452

answers:

3

In C#4.0 we're going to get dynamic types, or objects whose "static type is dynamic", according to Anders. This will allow any method invocation resolution to happen at runtime rather than compile time. But will there be facility to bind the dynamic object to some sort of contract (and thereby also get full intellisense for it back), rather than allowing any call on it even if you know that is not likely to be valid.

I.e. instead of just

dynamic foo = GetSomeDynamicObject();

have the ability to cast or transform it to constrain it to a known contract, such as

IFoo foo2 = foo.To<IFoo>;

or even just

IFoo foo2 = foo as IFoo;

Can't find anything like that in the existing materials for C#4.0, but it seems like a logical extension of the dynamic paradigm. Anyone with more info?

+2  A: 

I'm not aware of anything really resembling duck typing, I'm afraid. I've blogged about the idea, but I don't expect any support. It probably wouldn't be too hard to use Reflection.Emit to make a class which will generate an implementation of any given interface, taking a dynamic object in the constructor and just proxying each call through to it. Not ideal, but it might be a stopgap.

Jon Skeet
+1  A: 

That's a cool idea. If I understand you, you're describing/proposing a capability of the CLR, whereby, when you try and cast a dynamic object to an interface, it should look at what methods/properties the dynamic object supports and see if it has ones that effectively implement that interface. Then the CLR would take care of 'implementing IFoo' on the object, so you can then cast the dynamic object to an IFoo. Almost certain that that will not be supported, but it's a interesting idea.

mackenir
It's less about 'implementing IFoo' since it would still be a dynamic object, i.e. invocation would still happen at runtime, but you could now pass it around as an IFoo, because you told the compiler that your dynamic object behaves like an IFoo
Arne Claassen
Yes, but if you want an IFoo to hand around, 'somebody' would need to cook up a passthrough IFoo implementation with the dynamic object behind it. This is what Jon Skeet is talking about above.
mackenir
You can implement this pretty easily today if you're willing to write the shim in Python or Ruby.
Curt Hagenlocher
A: 

Tobias Hertkorn answered my question here with a link to his blogpost showing an example of how to use the Convert() method on MetaObject to return a dynamic proxy. It looks very promising.

Rasmus Faber
Interesting article, but really the work is in Castle's DynamicProxy which i use today to create "duck" types, so dynamic doesn't seem to bring anything to the party here. I was hoping dynamic would remove my need for DynamicProxy
Arne Claassen