create a generic wrapper class which will call the methods with lambda expressions

c# expression-trees generics lambda

Question

I am struggling to create a generic wrapper class which will call the methods with lambda expressions.

The code looks like this:

The Wrapper Class:

public class Service<T>
{
    private T instance;

    public Service(T param)
    {
        this.instance = param;
    }

    public void Call<U>(Expression<Func<T, U>> aExpression, Action<U> returnClass)
    {
        var methodCallExpr = aExpression.Body as MethodCallExpression
        var lambdaToFunc = Expression.Lambda(methodCallExpr).Compile();
        returnClass((U)lambdaToFunc.DynamicInvoke());
    }
}

The class which is wrapped:

public class Person
{
    public int GetPersonById(int bbb)
    {
        return bbb;
    }
}

The place where I made the call:

var serviceWrapper = new Service<Person>(new Person());
serviceWrapper.Call(x =>x.GetPersonById(2),Console.WriteLine);

I guess i have to atatch the instance of the object which is "instance" to the method expression but I don't know how..

When I run this code i get this exception :

Variable 'x' of type 'AsynCtry.Person' referenced from scope '', but it is not defined.

Is there a way to do this?

Accepted Answer

You don't need expressions for this - just use delegates directly:

public void Call<U>(Func<T, U> aExpression, Action<U> returnClass)
{
    U result = aExpression(this.instance);
    returnClass(result);
}

Your method call should function, then:

var serviceWrapper = new Service<Person>(new Person());
serviceWrapper.Call(x => x.GetPersonById(2), u => Console.WriteLine(u));


Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Is this KB legal? Yes, learn why
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Is this KB legal? Yes, learn why