I’ve not played with the VS2010 CTP much yet, and I’ve only looked briefly at the documentation and blogs about the new C# 4.0
dynamic type, but a thought occurred to me: why not have the option of making it generic as a way of saying “I will dynamically support this set of operations”?
As an example of what I mean, suppose you have an interface
IMessageRouter like this:
void Send(string message, string destination);
(This is an arbitrary example, by the way. The idea isn’t specifically more suitable for message routing than anything else.)
I may have various implementations, written in various languages (or COM) which support the
Send method with those parameters. Some of those implementations actually implement
IMessageRouter but some don’t. I’d like to be able to do the following:
// This is fine (but still invoked dynamically)
// Compilation error: no such overload
router.Send(“message”, “email@example.com”, 20);
Intellisense would work, and we’d still have some of the benefits of static typing but without the implementations having to know about your interface. Of course, it would be quite easy to create an implementation of the interface which did exactly this – but now imagine that instead of
IMessageRouter we had
MessageRouter – a concrete class. In this case the compiler would still restrict the caller to the public API of the class, but it wouldn’t have to be the real class. No checking would be performed by the compiler that your dynamic type actually supported the operations – given that we’re talking about dynamic invocation, that would be impossible to do. It would instead be an “opt-in” restriction the client places on themselves. It could also potentially help with performance – if the binding involved realised that the actual type of the dynamic object natively implemented the interface or was/derived from the class, then no real dynamic calls need be made; just route all directly.
This may all sound a bit fuzzy – I’m extremely sleepy, to be honest – but I think it’s a potentially interesting idea. Thoughts?