Fabio Milheiro
Fabio Milheiro

Reputation: 8484

C# Is there a way to create functions that accept anonymous function code as argument?

I would like to do something like

NameOfTheMethod(parameters){
  // Code...
}

There's using, foreach, for, etc. that are already built-in, but I don't know if creating something similar is even possible. Is it?

The reason why I ask this is because sometimes that there are many different pieces of code that are wrapped by basically the same code (examples are opening a connection to the database, creating the command, settings the datareader, testing if an element exists in cache and, if not, go get it, otherwise get it from cache, etc.)

Upvotes: 1

Views: 131

Answers (1)

Mehrdad Afshari
Mehrdad Afshari

Reputation: 422280

Yes, you can take a delegate instance as an argument:

void MyMethod(Func<Arg1Type, Arg2Type, ReturnType> worker) {
    Arg1Type val1 = something;
    Arg2Type val2 = somethingelse;
    ReturnType retVal = worker(something, somethingelse);
    // ...
}

You'd call it like:

MyMethod((arg1, arg2) => {
  // do something here with the arguments
  return result;
});

Upvotes: 5

Related Questions