Search code examples
genericsparameterslambdatypesexpression-trees

How to build generic type parameter


I have a question. How can I build a generic type parameter? I am trying to build an expression tree and I have the following line to build:

var expression = Expression
                .Lambda<Func<T, bool>>(
                    operation,
                    new ParameterExpression[] {parameter});

So it is expected that I specify type parameter for T in .Lambda> but the type parameter T in not known until runtime.

Please help. Thanks


Solution

  • Well, you could write it in a generic method:

    public Expression<Func<T,bool>> BuildExpression<T>(...)
    {
        // Whatever you need to do
        var expression = Expression
                .Lambda<Func<T, bool>>(
                    operation,
                    new ParameterExpression[] {parameter});
    }
    

    ... and then call that method via reflection. Alternatively:

    Without knowing anything more about your requirements, it's very hard to give any advice about which of these would be the most suitable approach. Please edit your question to give more details.