Creating an Expression that returns an object

84 Views Asked by At

I have this method:

public R TranslateExpression<R>(Expression exp)
       where R : DbRequest
{
           //...
}

In another class I have the following method:

public void Persist(E entity)
{
     Expression expr = Expression.Return(entity); //Does not compile, but I'm looking for something like this

     PersistRequest request = TranslateExpression<PersistRequest>(expr);
}

How can I create an Expression that simply returns an instance?

Something like this: () => { return entity; }.

1

There are 1 best solutions below

1
On BEST ANSWER

You can create an Expression<Func<E>> and then use a lambda expression to return your entity once the expression is invoked.

public void Persist<E>(E entity)
{
    Expression<Func<E>> expr = () => entity;    
    PersistRequest request = TranslateExpression<PersistRequest>(expr);
}

public R TranslateExpression<R>(Expression exp)
       where R : DbRequest
{
}

However, your TranslateExpression method is not particularly useful at this point since you've lost the power of your expression. Unless you're doing something special inside of TranslateExpression, it might be better suited to something like the following signature:

public R TranslateExpression<R, E>(Expression<Func<E>> exp)
       where R : DbRequest
{
}