1

I have done a lot of PHP in the past and there you where able to pass trough code as a parameter, if Im right it was called a callable.

This is how it looked like:

METHOD('Parameter', function() { 
echo "Hey!";
});

is This possible in C#? Cause I would love to do that. to execute that function as a paramenter in a method.

2 Answers 2

4

If I understand correctly, you want to pass in a callable function to another method? The easiest way to do that would be to use a Func or Action parameter:

void MyMethod(Action<string> passedInFunc)
{
    passedInFunc("Hey");
}

And then call it:

MyMethod(s => 
{
    Console.WriteLine(s);
});

An Action represents a function that do not return any value, while a Func is a function that does return a value.

If you do not want to pass in any arguments to your Action, there is a non-generic version you can use.

In the end, these are just delegates, so you could also define your own custom delegate and pass that one instead.

2
  • Thanks, after I posted it LambaExpression game into me and I figgured it out. But couldn't find this question back. Ill awnser it myself. Thanks anyways! Mar 20, 2016 at 19:40
  • @joey FYI in the middle of the top bar, you can click on your avatar to access your profile. There you can find the questions you asked. Mar 20, 2016 at 19:56
0

My awnser that I found quickly after posting this question:

Usage:

TestMethod ("Lambda", () => {
  Console.WriteLine("Expression");
});

Method:

public void TestMethod (string name, Action action) {
 if(name == "Lambda") {
   action.Invoke ();
 }
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.