C# To Support Dynamic Typing
January 30, 2008 by Philippe Mougin
From Charlie Calvert’s Community Blog:
The next version of Visual Studio will provide a common infrastructure that will enable all .NET languages, including C#, to optionally resolve names in a program at runtime instead of compile time.
[...] C# developers can currently use reflection to instantiate classes and call arbitrary methods that are not known at compile time. The dynamic extensions to the C# language will make it much easier to make such calls.
The C# team’s plans for the actual syntax are still evolving. For example, they are pondering over the introduction of a dynamic keyword to mark code blocks inside which this feature would be activated. So, for instance, we could have:
dynamic
{
myObject.foo();
}
Where the foo() method would not have to be declared anywhere. The variable myObject could just be declared to be of type object, and this would compile.
In dynamic object-oriented languages such as Objective-C, Smalltalk or Ruby, this feature is the default and is a tremendous source of simplicity and power. If this can be grafted without too much problems or crippling (how is it going to interact with the existing rules such as overriding, how will it handle absent methods at run-time, etc.) this could be a giant leap forward for C#.
And then, I expect to see it discussed for inclusion in Java soon.
An other maybe better option is like how scala does this
http://neilbartlett.name/blog/2007/09/13/statically-checked-duck-typing-in-scala/
This a tremendous source of simplicity and power… and can make for some very elegant solutions. Add to this, the ability to add methods run-time (like javascript).
However, this power comes at a cost. If you call a method which does not exist, it would be a run-time error, not a compile-time error. This isn’t a big deal for interpreted languages - they don’t have a compile-time. However, the ability to find these errors before the code is run is a key benefit of compiled code.
Like most things in software engineering, there is a tradeoff.
I think having it optional is a good idea. You can normally take advantage of the compile-time method existence checks… but if you have a specific solution which would benefit from dynamic typing, that technique is still available.
Why not just use VB.NET with Option Strict Off?