Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# 4.0, Methods on the fly?

Tags:

c#-4.0

With the introduction of things like duck typing, I would love it if I compose object methods on the fly, besides extension methods. Anybody know if this is possible? I know that MS is worried about composing framework on the fly, but they seem to be dipping their toes in the water.

Update: Thanks to Pavel for clarifying. For example, say I return a new dynamic object from LINQ and would like to add some methods to it on the fly.

like image 418
Trent Avatar asked Nov 02 '09 18:11

Trent


2 Answers

In light of the updated answer, you're actually not looking for "dynamic methods", so much so as "dynamic objects" - such that you may add new properties and methods to them at runtime. If that is correct, then in .NET 4.0, you can use ExpandoObject in conjunction with dynamic:

dynamic foo = new ExpandoObject();
foo.Bar = 123; // creates a new property on the fly
int x = foo.Bar; // 123

// add a new method (well, a delegate property, but it's callable as method)
foo.Baz = (Func<int, int, int>)
    delegate(int x, int y)
    {
        return x + y;
    };

foo.Baz(1, 2); // 3

You can have "dynamic methods" too, with expression trees, and once you obtain a delegate for such a method, you can also create a callable method-like property out of it on an ExpandoObject.

For use in LINQ queries, unfortunately, you cannot use object initializers with ExpandoObject; in the simplest case, the following will not compile:

var foo =  new ExpandoObject { Bar = 123; }

The reason is that Bar in this case will be looked up statically as a property of ExpandoObject. You need the receiver to be dynamic for this feature to kick in, and there's no way to make it that inside an object initializer. As a workaround for use in LINQ, consider this helper extension method:

public static dynamic With(this ExpandoObject o, Action<dynamic> init)
{
     init(o);
     return o;
}

Now you can use it thus:

from x in xs
select new ExpandoObject().With(o => {
    o.Foo = x;
    o.Bar = (Func<int, int>)delegate(int y) { return x + y; };
});
like image 180
Pavel Minaev Avatar answered Sep 20 '22 19:09

Pavel Minaev


Yes, there is: Generating Dynamic Methods with Expression Trees in Visual Studio 2010

like image 29
Alexandra Rusina Avatar answered Sep 17 '22 19:09

Alexandra Rusina