Home > front end >  How to declare Type for a params list of lambda expressions?
How to declare Type for a params list of lambda expressions?

Time:02-28

I'm trying to build a method which takes a params list (i.e., a comma-separated list) of lambda expressions.

public void DoSomething<TDataType, ...>(params Expression<Func<TDataType, TNavProp>>[] properties)
{
    // ...
}

How can I declare TNavProp in a way which allows multiple different types?

For example...

public class Class1
{
    public int IntProp { get; set;}

    public string StringProp { get; set; }
}

DoSomething<Class1, int>(cl => cl.IntProp);    // this compiles
DoSomething<Class1, ?>(cl => cl.IntProp, cl => cl.StringProp);    // this won't compile

Is the only solution to declare multiple overloads of DoSomething, each with successively more expression arguments?

Inside the method, I actually only want to record the PropertyInfo (I would even settle for the property name, as a last resort), so is there a simpler way of achieving that?

CodePudding user response:

In your case, because you simply need the PropertyInfo related to each expression, and the return type is not a concern, you can use object as your TReturn:

public static void DoSomething<TDataType>(
    params Expression<Func<TDataType, object>>[] properties)

Now this is valid, because each lambda can be converted into a Expression<Func<Class1, object>>:

DoSomething<Class1>(cl => cl.IntProp, cl => cl.StringProp);
  • Related