user4367090
user4367090

Reputation:

How to put a lambda expression in a variable and then pass it to a s/r

Sorry for this question: I am somehow new to lambda expressions. I have a library and some functions and I want to pass the to execute some actions. Therefore I thought about putting some code in a lamba expression, associate it to a variable and the make it execute from the library s/r. In short (pseudocode):

var1 = { ...code1...};
var2 = { ...code2...};
ExternalFunction(??? var1, ??? var2);


ExternalFunc(??? var1, ???var2)
{
  Console.WriteLine("Executing code 1");
  ???

  Console.WriteLine("Executing code 2");
  ???
}

Upvotes: 1

Views: 3307

Answers (2)

MakePeaceGreatAgain
MakePeaceGreatAgain

Reputation: 37000

Depending on what your code should do you will need a parameter of type Action<T1, T2, ...> or Func<T1, T2, ...>. However you cannot create your method so that it runs any arbitrary code, you have to provide a return-type and the parameters of course.

So if your code of block returns an int and expects a string you may write this:

Func<string, int> myFunc = x => Convert.ToInt32(x) + 1;

void ExternalFunc(Func<T1, T2> myFunc, T1 param) {
    var myInt = myFunc(param);
}

Now call it like this:

ExternalFunc(myFunc, "1");

However you cannot expect this code to run also:

Func<int> myOtherFunc = () => 1;
ExternalFunc(myOtherFunc)

because myOtherFunc must be of type Func<T1, T2>, not just Func<T> to be passed to ExternalFunc.

Moreover if your code-block should not return anything (void), use an Action<...> instead of Func<...>.

Upvotes: 2

dylanthelion
dylanthelion

Reputation: 1770

Well, here's your standard documentation for lambdas:

https://msdn.microsoft.com/en-us/library/bb397687.aspx?f=255&MSPPError=-2147217396

if you're looking for the type inference of a lambda, it's a Func. So the parameter text you're looking for is probably this:

public void youtExternalFunction(Func<> var1, Func<T, U> var2)

Upvotes: 0

Related Questions