2

I'd like to build Expression for something like this:

x => DoSomething(x)

Is it possible and how can I accomplish this?

Sergey Litvinov
  • 7,408
  • 5
  • 46
  • 67
pangular
  • 699
  • 7
  • 27

3 Answers3

1

You can do like this:

using System;
using System.Linq.Expressions;

public class Program
{
    public static void Main()
    {
        Expression<Func<string, string>> func = (x) => DoSomething(x);

        Console.WriteLine(func.ToString());
    }

    public static string DoSomething(string s)
    {
        return s; // just as sample
    }
}

Here is working fiddle - https://dotnetfiddle.net/j1YKpM It will be parsed and Lambda will be saved as Expression

Sergey Litvinov
  • 7,408
  • 5
  • 46
  • 67
0

Do you mean Func<Tin,Tout> delegate?

Basically you need a Func<Tin,Tout>

Func<Tin,Tout> func = x=> DoSomething(x)

where x is of type Tin and DoSomething return Tout type

Nick
  • 4,192
  • 1
  • 19
  • 30
0

Maybe the question was a bit unclear. This is what I meant:

var arg = Expression.Parameter(pluginType, "x");
var method = GetType().GetMethod("DoSomething");
var methodCall = Expression.Call(method, arg);
var lambda = Expression.Lambda(delegateType, methodCall, arg); // I was looking for this

Thats what I wanted. Thanks for your time :)

pangular
  • 699
  • 7
  • 27
  • 1
    if you don't need to do it in runtime and you know signature, then you can always use such code `Expression> func = (x) => DoSomething(x);` as it will generate almost the same code as in your answer. – Sergey Litvinov May 13 '14 at 21:54
  • Yes, this was only a small part of a bigger (already solved) problem. I had to do it all in runtime. Спасибо :) – pangular May 13 '14 at 22:06
  • 1
    If you are interested, here's the complete problem that I was struggling against: http://stackoverflow.com/questions/23593914/interception-using-structuremap-3/23642317#23642317 – pangular May 13 '14 at 22:06
  • i got it, yeah, then it makes sense. you are welcome :) – Sergey Litvinov May 13 '14 at 22:08