Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing a Function (with parameters) as a parameter?

I want to create a generic to which I can pass a function as a parameter, however this function may include parameters itself so...

int foo = GetCachedValue("LastFoo", methodToGetFoo) 

Such that:

protected int methodToGetFoo(DateTime today) { return 2; // example only } 

Essentially I want to have a method that will check the cache for a value, otherwise will generate the value based on the passed in method.

Thoughts?

like image 661
klkitchens Avatar asked Mar 02 '09 21:03

klkitchens


People also ask

How do you pass a function with a parameter?

Use a "closure": $(edit_link). click(function(){ return changeViewMode(myvar); }); This creates an anonymous temporary function wrapper that knows about the parameter and passes it to the actual callback implementation.

Can we pass function as parameter?

Because functions are objects we can pass them as arguments to other functions. Functions that can accept other functions as arguments are also called higher-order functions. In the example below, a function greet is created which takes a function as an argument.

Can I pass function as parameter in JavaScript?

Functions in the functional programming paradigm can be passed to other functions as parameters. These functions are called callbacks. Callback functions can be passed as arguments by directly passing the function's name and not involving them.

Can you pass functions as parameters in C?

We cannot pass the function as an argument to another function. But we can pass the reference of a function as a parameter by using a function pointer.


2 Answers

It sounds like you want a Func<T>:

T GetCachedValue<T>(string key, Func<T> method) {      T value;      if(!cache.TryGetValue(key, out value)) {          value = method();          cache[key] = value;      }      return value; } 

The caller can then wrap this in many ways; for simple functions:

int i = GetCachedValue("Foo", GetNextValue); ... int GetNextValue() {...} 

or where arguments are involved, a closure:

var bar = ... int i = GetCachedValue("Foo", () => GetNextValue(bar)); 
like image 140
Marc Gravell Avatar answered Sep 19 '22 20:09

Marc Gravell


Use System.Action and a lambda expression (anonymous method). For example:

public void myMethod(int integer) {          // Do something }  public void passFunction(System.Action methodWithParameters) {     // Invoke     methodWithParameters(); }  // ...  // Pass anonymous method using lambda expression passFunction(() => myMethod(1234)); 
like image 43
empirico gutierrez Avatar answered Sep 20 '22 20:09

empirico gutierrez