wsyq1n
wsyq1n

Reputation: 117

Lookup a lambda expression in a dictionary by a key, and then use it?

Sorry for the newbie question, but how would you:

  1. call a dictionary with a lambda expression as the value
  2. run that lambda expression with a variable as an argument and capture the return value.

javascript version would be like:

function LookUpAndDo(num, funcName) {
   const dictionary = {
      myFunc: (x) => { return x},
   }

   const runThis = dictionary[funcName];

   return runThis(num)
}

LookUpAndDo(5, "myFunc");
// returns 5

Upvotes: 0

Views: 254

Answers (1)

Ortiga
Ortiga

Reputation: 8824

This method is pretty straightforward to convert to C#

private T LookUpAndDo<T>(T param, string funcName)
{
    var dict = new Dictionary<string, Func<T, T>>{
        { "myFunc", x => x }
    };
    
    var func = dict[funcName];
    
    return func.Invoke(param);
}

And you may invoke it as LookUpAndDo(5, "myFunc");

In the case Func parameter and return types does not match, then you'd have to specify both types in the generic method:

private TResult LookUpAndDo<T, TResult>(T param, string funcName)
{
    var dict = new Dictionary<string, Func<T, TResult>>{
        { "myFunc", x => x.ToString() }
    };
    
    var func = dict[funcName];
    
    return func.Invoke(param);
}

And since C# can't infer return types, you'd have to call passing both type parameters, as: LookUpAndDo<int, string>(5, "myFunc");

Upvotes: 1

Related Questions