tags:

views:

223

answers:

1

I know that anonymous functions are not supported as arguments to a dynamic method call. What are other such limitations of DLR in .NET 4.0?

+9  A: 

You can use anonymous functions, you just have to cast them first:

dynamic list = new List<string>() { "10", "20" };
dynamic converted = list.ConvertAll((Func<string, int>) (x => int.Parse(x)));

The same is true of method group conversions:

foo.Click += (EventHandler) MyClickHandler;

Other restrictions I've encountered so far:

  • Static methods and constructors can't be dynamic in terms of the type, but can be dynamic in terms of the arguments
  • You can't use dynamic in a type constraint
  • You can't use dynamic as a type argument in an interface for a class declaration, but you can use it as a type argument for a base class, i.e.

    class Invalid : IEnumerable<dynamic>
    class Valid : List<dynamic>
    
  • Extension methods aren't discoverable at execution time (but you can call the static method directly with dynamic arguments)

  • There's a bug in 4.0b1 such that you can't convert from dynamic[] to IEnumerable<dynamic> - that will be fixed for the release.
  • You can't use dynamic as a base class

(Note that these are limitations of C# 4.0 as much as of the DLR itself. I got the impression that was what you meant though.)

Jon Skeet
Great, good to get an answer from you :)
amazedsaint
Don't all uses of delegates need the cast, not just anons/lambdas? e.g. in btn.Click += MyClickHandler; if btn is dynamic but does have a Click event, that won't work. You need the cast around the MyClickHandler method name.
Daniel Earwicker
@Earwicker: Not *all* uses of delegates, but you're right that method group conversions require a cast as well. Will update my answer accordingly.
Jon Skeet