tags:

views:

87

answers:

2

I understand that the new ‘dynamic’ keyword in C# 4.0 facilitates interaction with dynamic .NET languages, and can help to cut code by using it instead of reflection. So usage is for very specific situations.

However, what I would like to know is if it will give C# all the dynamic benefits that one would get in other dynamic languages such is the IronXXX languages? In other words, will it be possible to write a entire application in C# in a dynamic language style?

And if it is possible, would it be recommended or not. And why, or why not respectively?

Will I get all the benefits of a dynamic language without switching to another language?

+1  A: 

While the dynamic keyword will definitely bring C# closer to the dynamic world it won't make it a dynamic language and by so it won't have the benefits of dynamic languages such as adding methods to an existing type at runtime, ...

Darin Dimitrov
+5  A: 

I wouldn't say C# is a first class dynamic language, no.

Firstly, some of the static typing features really don't play well with dynamic typing. For example:

public void ShowListCount(IList foo)
{
    dynamic d = foo;
    Console.WriteLine(d.Count);
}

That looks like it should always work, because IList exposes Count, right? Try it with this:

ShowListCount(new int[10]);

Bang. Arrays implement IList.Count with explicit interface implementation, so when dynamic typing "sees" the object as an array, it doesn't look see the Count property. There are various gotchas like that.

Also, if you want to implement dynamic behaviour in C# (i.e. being called dynamically), there's no explicit language support. You can derive from DynamicObject or implement IDynamicMetaObjectProvider yourself, but nothing in the language is going to help you.

I regard dynamic typing in C# as something to be used primarily when you want to interoperate with an existing dynamic platform such as IronPython or a weakly-typed COM API. There are some places where it can be useful within pure C#, but they're relatively rare.

Basically C# is still very obviously a language designed with static typing in mind. Having the ability to use dynamic typing carefully where you want it is nice, but if you want to use dynamic typing extensively for one area of your codebase, I'd suggest writing that bit in IronPython and then calling into it from C#.

Jon Skeet
Thank you. Very clear and informative answer.Interesting gotcha about the explicit interface implementation.
Jacques Bosch