views:

3622

answers:

22

Hi all,

I've just seen an article detailing the new C#4.0 'dynamic' feature previewed at the PDC 2008 and I wondered what people thought of it ? I'm wondering:

  • what are good examples of the benefit of such an addition to the language
  • possible disadvantages
  • performance implications

I guess people with experience of dynamic languages or else any lucky soul with the 2010 CTPs from PDC may have given it a whirl...

UPDATE: Please do keep posting your thoughts, it's kinda cool to see lists of for / against arguments and, at the very least times that it'll be appropriate and issues to consider.

Benefits:

Potential issues:

+8  A: 

I see this feature, and the first thing which pops into my mind is the message-oriented architecture of Objective-C. Very cool and powerful, if used appropriately. I haven't had the problem space this addresses yet, but I could definitely see places where it would be useful functionality to have.

The blog post you link to discusses performance somewhat, but bear in mind that CTPs are exactly that: Previews. Until release time, performance measurements don't mean anything.

But wicked cool, nonetheless. The ability to cleanly deal with unknown types rocks verily.

John Rudy
+9  A: 

Smells like a duck.

kenny
IUnknown + IDynamicObject = duck.
Justice
Or, IDispatch. I'm not a COM dude.
Justice
Hi, ho, hi, ho, it's off to where I go?
kenny
Surely, IUnknown + IDynamicObject = IDuck?
AJ
+2  A: 

This has been available in boo for a while as duck typing. It also harks back to Visual Basic and COM's IDispatch.

I think it is a worthwhile addition, but am not sure it will prove broadly useful. You need to have a class you know will have a method with a given name at some point in the future but doesn't now.

Reflection obviously lets you specify the method (or property) name at runtime, this doesn't (at least as described in the article).

I'd like to have syntax that lets me write something like:

string method = "Zot";
obj.method();

Where the method name can be supplied at runtime too.

Rob Walker
Why not program in a language that isn't built to be C-like then? This stuff seems woefully out of place in a strongly typed language like C#.
SoloBold
Do you mean like ".send" in ruby? That would be cool, but I'd like to see other things (such as symbols) well ahead of that. TBH you can probably write your own version of .send using reflection and InvokeMember anyway
Orion Edwards
Then make an extension method on object, which accepts a string for invocation. Would actually be pretty lean I guess...
Erik van Brakel
+11  A: 

Microsoft has a document describing the reasoning around the new features. It tells you the motivation for them in a prosaic nice way. (Read it!) It talks a lot about using COM and dynamic-language objects from managed code.

Hugo
"A secondary theme is co-evolution with Visual Basic." Uh-oh ;}
SoloBold
Heh. There's been a lot of whining in the VB world about being some sort of second class citizen. I won't really buy it until I see exception filters in C#.
Greg D
The link was dead. Could you please give me the title of that document, or upload it if possible? Thanks.
Hai Minh Nguyen
+6  A: 

Having recently been buried in IDispatch and .NET, I welcome anything that might make it easier (or even work properly). There are many gotchas in the Interop world and I think that the dynamic keyword as well as the abilities to call-by-name, and provide default values will make this much easier to deal with from within C#.

Jeff Yates
+1  A: 

I dislike it.

Runtime method dispatch is available via reflection, making it easy like this will just make it prone to abuse.

FlySwat
What sort of abuse? Please share -- http://stackoverflow.com/questions/245318/c4-dynamic-keyword-why-not
Erik Forbes
+4  A: 

Why not program in a language that isn't built to be C-like? This stuff seems woefully out of place in a strongly-typed language like C#. There's nothing this does that a good application of interfaces and/or inheritance doesn't solve more cleanly in a C-like language. Plus interfaces and inheritance can be checked at compile time.

Someone mentioned objective-C's messaging (well really it was first widely implemented in SmallTalk). This is similar. While I enjoy that feature set in ObjC, what is it doing in C#? Is it adding anything useful? Is it adding anything that a library couldn't add? No. Instead, it needlessly muddies the language and changes its purpose. C# is great partly because it is strongly typed.

There are already good dynamically-typed languages such as Python. They are good if you problem fits their domain and you like using them. Some of us prefer strongly-typed languages and the explicit nature of code written for them. They are both valid paradigms, so don't let someone tell you one makes you more productive (for which types of programs? Under what circumstances?). Writing bank software in Python would be stupid as would writing simple scripts in C#. For everything in between, strongly- and dynamically-typed languages are about even - and that gives developers choice and the ability to code in a style they like.

I'm just saying use the right tools for the job. Don't try to bend a hammer into a screwdriver when you have a screwdriver right next to you.

If you wanted to add something to C# how about more features from the functional programming and/or concurrency world? That could add something and take C# forward; this takes C# in circles.

SoloBold
+1, interesting take. (I was the guy who mentioned ObjC. And you're right about Smalltalk; I forgot about that. :) )
John Rudy
One of the most important use cases of "dynamic" (in my opinion, of course :) is *interoperability with* Python or Ruby. I agree that a large body of dynamic code should stay in a purely dynamic language, but this vastly simplifies interop for things like embedded scripting.
Curt Hagenlocher
I'm starting to understand the usefulness for interacting with dynamic languages... I still feel like there should be a better way :)
SoloBold
Why do you say "for dynamic, go to Python" but not "for functional go to F#/ocaml/whatever"?
Jay Bazuzi
I... I didn't say "for dynamic, go to Python?" :)
SoloBold
"woefully out of place in a strongly-typed language like C#" - surely you mean "in a *statically*-typed language like C#"? C# is both, but only the latter conflicts with "dynamic".
romkyns
surely that is what i meant lol
SoloBold
I think it's more interoperability than trying to bend a hammer. With "dynamic" C# can interop with DLR dynamic languages nicely, vice versa. Functional? That's where F# comes in. The key selling point of the .NET stack is that you don't need to just pick C# or Pythob or F# anymore; you get it all. You can develop your app using general purpose language (C#) as the backbone. For dynamic languages/scripting, you've got IronPython/IronRuby. If certain part of your app is better expressed in functional construct, you've got F#. Lastly, administrate your app all through PowerShell. That's power!
ShaChris23
+10  A: 

I'm sincerely disappointed by this new addition.

Compile-time type safety is a massively effective mechanism for eliminating a whole class of bugs.

Bugs that can't be detected until runtime can be very dangerous, particularly if they're associated with edge conditions.

While I acknowledge the need for dynamic typing in certain circumstances, I really think this should be an explicit opt-in design decision, either through the use of a compiler pragma or (preferably, IMO) from a different assembly written in a dynamically-typed language.

Factor in the performance overhead and there's very little positive about it for me.

Steve Morgan
Yet it is an explicit opt-in -- you need to use the new dynamic keyword to use this feature ... I get where you're coming from, of course, but I do think there are positives here. (FWIW, I generally prefer strong typing as well!)
John Rudy
Forget about bugs, what about documentation? That's one thing that static types afford that hardly anyone ever talks about. I can go look-up the type from its use and find out what it does. How do I lookup what dynamic q does? What is dynamic q? Who knows!?
Robert C. Barth
You don't have compile-time safety anyway, since everything you can now do with `dynamic` you could already do with reflection. This makes the dynamic programming we were doing anyway easier and more useful.
Justice
I'm starting to understand the usefulness for interacting with dynamic languages... I still feel like there should be a better way :)
SoloBold
Oops... wrong thread...
SoloBold
Is your objection to dynamic programming in general, or to this specific modification to C#?
Jay Bazuzi
@Jay: for me it's in general. Quite frankly it leads to runtime disasters and will be abused by a lot of people.
Chris Lively
+26  A: 

This really is an explicit opt-in design decision -- you have to explicitly use the dynamic keyword in order to opt-in. :) There are hundreds of ways to write faulty code, and only some of them are caught by static type checks. If you have proper test coverage of your code, then you'll know it's working the way you expect even with dynamic types.

I love dynamic, but then I'm totally biased.

Edit: with regard to performance, the first trip through any dynamic call site is going to be very expensive compared to a normal method call. But subsequent calls should be roughly as expensive as a call through a delegate. That's because information is actually cached at the call site so it's not regenerated on subsequent calls.

Edit 2: I'm a bit curious as to why people think this would be "abused"? Some newbie programmer is going to make his or her code compile correctly by avoiding explicit types where possible and therefore losing out on Intellisense? That hardly seems likely.

Links:

Curt Hagenlocher
I think the consequences are too serious for the use of the word "dynamic" in place of a return type to be sufficiently explicit. Better to have the code in a different assembly which is specifically built for dynamic typing. Don't weaken the language and rely on testing best-practice to rectify.
Steve Morgan
Not sure why this got down votes - Some people just can agree to disagree. The point it no one is forcing to use it, and it can be handy in the right places - Too bad you get down votes for an opinion like that...
Hugoware
Here here, I was surprised at the reaction - I thought it was an hopnest opinion and a fair point. I'm looking for pros and cons here...
ip
Concerning the performance, I'm using this with reflection and it's faster than method.Invoke
TimothyP
The dynamic keyword makes working with dynamic languages a lot easier. If you're just going to require another level of indirection because you think something is going to be abused, then you haven't reduced the likelihood of abuse, just required more hurdles and increased the amount of knowledge necessary to get it done. Dynamic solves problems that were being solved poorly by reflection. Reflection didn't produce the huge quantities of bad code that many people predicted it would. Dynamic will be abused, but not anything that will kill the language. And compared to reflection, it's cleaner.
Orion Adrian
+5  A: 

It's amazing how instead of going in the right direction (Spec#), the design team is going in the wrong one (DLR).

The dynamic keyword is going be abused so much... C# is on its way to becoming PHP.

Edit: I've written much more thoroughly about this on my blog, with a suggestion on how to improve the feature that you might find interesting.

Omer van Kloeten
Many language features have the potential for abuse. Extension methods and generics are 2 examples. I think the key is, will 'dynamic' help devs with COM, Office, and dynamic language interop more than it hurts them through foolish developer abuses? That's yet to be seen.
Judah Himango
Potentially damaging a language's integrity and strength only to appease those people working with COM, an 18 year old technology... Hum.
Omer van Kloeten
Omer - why do you feel this way? Please share -- http://stackoverflow.com/questions/245318/c4-dynamic-keyword-why-not
Erik Forbes
I agree with Omer. Exactly how many developers are suffering through COM-interop problems? Now, a mess of COM-interop developers will chime-in, but that's not exactly representative of the entire installed-base for c#.
Robert C. Barth
Just for COM interop? What about XML interop or Python interop?
Curt Hagenlocher
"feature is powerful" and "feature is dangerous" nearly always come together.
Jay Bazuzi
+1  A: 

The pink elephant here is the crappy developers who will make their entire codebase dynamic because it's "easier" or "faster" or whatever silly excuse is usually given for poorly-designed, fragile software, and then you'll get to inherit that mess, and you'll curse the day the word "dynamic" made its way into the C# specification. Because, the simple truth is this: if it's there, people will abuse it. Especially those that don't know any better. And there are a lot of those people in the software engineering field.

Robert C. Barth
And if those people don't abuse dynamic, they'll abuse something else... I don't believe that "protection from stupidity" is a valid reason to hold back the people who aren't stupid...
Orion Edwards
A: 

The late-binding is not really what I was stoked about. I like the co- and contravariance feature. It means that the CLR is moving closer to Haskell style type class definition which would be cool.

I don't see how the dynamic keyword is a new feature. It seems like plain old reflection to me you just have a keyword for it now. So do you want them to get rid of reflection? Did reflection become a bad thing because it now has a keyword associated to it? I hope not as it is a very handy tool. I agree with Mr Barth. People abuse reflection all the time because the don't know any better. So really, what's changed?

Thedric Walker
Compare the new dynamic facility with the same thing implemented via reflection, and it will be clear as day how this facility is not 'plain old reflection', any more than C# is 'plain old IL'.
mackenir
One of the primary usages for reflection is to enable late-binding in languages that don't support it out of the box. The dynamic keyword seems to just encapsulates this.
Thedric Walker
@mackenir Nah--no way reflection is going away. The `dynamic` keyword just exists to make certain kinds of reflection patterns trivial to implement. You'll still be able to use the existing reflection facilities to fill in any behaviors that isn't already built in to `dynamic`.
sblom
Yes, sblom. I agree, but am a bit confused that you directed your comment at me. :)
mackenir
A: 

It's awesome. The only thing wrong with it, is that it's not called var

dynamic is too long a word to be used like that. It's similar to if they made you type integer everywhere instead of just int

To clarify: Ideally I would like to be able to use var everywhere, and if the compiler can infer the type, it would, and if not, it would be dynamic. I realise this may not be possible/practical - so for a more realistic solution, I'd like to see the keyword be dyn or dvar or something like that, just to cut down on typing.

Orion Edwards
They already have a var keyword as of 3.0... And it's actually less useful then the dynamic keyword.
nlaq
The idea is to distinguish between the strongly-typed 'var'-variables and the dynamically-typed 'dynamic'-variables. I think there is no way the var keyword can be reused for dynamic types without messing things up.
JacobE
The var keyword should have been called "infered" insteadand dynamic is a type, not a keyword
TimothyP
+1  A: 

dynamic is awesome.

now just give method missing so i don't have to write those classes in ruby.

ignu
I *think* the equivalent of method_missing is to implement IDynamicObject.
mackenir
+2  A: 

Dynamic languages are coming to .Net, and C# has to support them. There will be libraries written in the likes of IronRuby and IronPython, and I will want to use them from C# code.

The dynamic type will let me do this easily. Sure, it could be done through reflection, but this way I don't need to clutter my code with noise. As somebody who remembers trying to use OLE controls through an IDispatch interface from C++, I welcome the dynamic keyword.

It will be abused, but that's a fact of life in our business. Show me a language feature that hasn't been bent to the will of a mad programmer on a mission.

Lee
+2  A: 

Deja vu... ...bringing back what was there in VB 3/4/5/6, "ole automation", com, IDispatch...

I think it will be a useful shortcut to reflection. As many have already pointed out, the potential for misuse is there, but the potential for misuse is always there in so many other language and CLR features.

Bad programmers will write bad code with or without it. Good programmers will write good code with or without it. It will bring a bit more productivity to both groups. (I.e. the bad programmers will write their bad code faster, the good ones will write their good code faster... :) ).

KristoferA - Huagati.com
+3  A: 

For me the most exciting part is the new dynamic dispatching features in C# 4.0. Dynamic dispatching provides a great way for resolving method calls at runtime. The new dynamic keyword can be used to create dynamic objects, much like

dynamic reader=new DynamicReader();
dynamic data=reader.Read();

Once you've a dynamic object, the compiler is least bothered about any method calls you might make on the dynamic object. The calls will be resolved only at the runtime. In this case, the method Read() is dispatched dynamically during run time.

What is more beautiful is, C# now gives you the flexibility to specify how the dynamic calls should be dispatched. You can implement the IDynamicObject, to write these binders yourself. For example,

public class DynamicReader : IDynamicObject
    {
        public MetaObject GetMetaObject
              (System.Linq.Expressions.Expression parameter)
        {
            return new DynamicReaderDispatch (parameter);
        }
    }

    public class DynamicReaderDispatch : MetaObject
    {
        public DynamicReaderDispatch (Expression parameter) 
                   : base(parameter, Restrictions.Empty){ }

        public override MetaObject Call(CallAction action, MetaObject[] args)
        {
            Console.WriteLine("Logic to dispatch Method '{0}'", action.Name);
            return this;
        }
    }
amazedsaint
A: 

The dynamic feature will be better understanded. It's just a question of imagination. Finding well designed patters to fit in the dynamic paradigm. I'm sure that a lot of programmers will propose stunning coding solutions that will make our coding more expresive and productive.

No imagination is needed, because these patterns can be borrowed from existing Python programs.
finnw
+5  A: 

Good example for using the C# dynamic keyword is in TDD.

This code doesn't compile because the method "Addition" is not implemented

[TestMethod()]
public void CalculatorThingAdd_2PositiveNumbers_ResultAdded()
{
    CalculatorThing myCalculator = new CalculatorThing();
    int result = 0; 
    int expcected = 3;

    // --> CalculatorThing  does not contain a definition for 'Addition'
    result = myCalculator.Addition(1, 2);

    Assert.AreEqual(result, expcected);
}

With the dynamic keyword the code compiles and the test fails! --> TDD
Because the method "Addition" is not implemented

[TestMethod()]
public void CalculatorThingAdd_2PositiveNumbers_ResultAdded()
{
    dynamic myCalculator = new CalculatorThing();
    int result = 0; 
    int expcected = 3;

    result = myCalculator.Addition(1, 2);

    Assert.AreEqual(result, expcected);

}

More details here

Peter Gfader
I'm not convinced - why is it better for the compilation to succeed and the test to fail? And why can't you implement a stub that throws an exception to achieve the _exact same effect_?
romkyns
what we want during TDD is a failing test not a failed compile (even on build server!)a stub that throws an exception is slightly harder :-)
Peter Gfader
Yes! This is the #1 reason I'm so excited about `dynamic` in C# 4.0! @romkyns, the biggest reason this is so great is that you can go write a few tests that define what you're going to build without having to actually start building--even stubs. That really does help separate "design thinking" from "implementation thinking".
sblom
A: 

I think a lot of those opposed to the dynamic keyword are assuming that it will get used and abused in pure C# code. The real benefit to dynamic is being able to interface with dynamic or clunky external contexts. For example, being able to reference Javascript objects in a Silverlight application using native language constructs is awesome. Working with Office or COM could also be much cleaner with dynamic.

However, I see little benefit in using it in pure C# applications. Static typing in C#, especially now that we have generics and implied typing, is not burdensome or difficult at all, so you'd might as well benefit from avoiding a large class of bugs.

Jacob
100% agreed. `var` takes care of many of the worthwhile "I don't want to think about this type" situations in C#.
sblom
A: 

As most of the developers here are aware, the problems of software development are not caused in any way whatsoever by the structure or capabilities of the tools. They put a man on the moon with sequential programming, and managed to get 3 guys in a metal bin back from the dark side of the moon using a slide rule and trig. You can't tell me that adding dynamic to C# is going to herald the end of the world. The problem is (poor) programmers and that problem, no matter what language gets invented, will never be solved.

richarddas