Search code examples
c#lambdaexpressionmethodinfo

Using a lambda expression to specify parameter of method


Given the MethodInfo of a method how can I use a lambda expression to specify a parameter (ParameterInfo)?

For example, given the following method signature:

public string DoSomething(int id, int count);

I would like to have a method:

WithParameter(MethodInfo info, Expression<???> expression);

Which would be invoked like so:

WithParameter(doSomethingMethodInfo, x => x.id) 

Is this possible?


Solution

  • If you want to specify the parameter name in statically safe way, this is not possible.
    Two reasons:

    1. C# does not generally support this for parameters
    2. MethodInfo had already lost all static type information

    Alternative approaches are different depending on your final goal.