tags:

views:

85

answers:

3

In c# we can create delegates via a variety of means (e.g. Action<>, Func<>, delegate, lambdas, etc). But when you invoke those methods, you have to provide the parameter values for the delegate you are invoking:

delegate int del(int i);   
del myDelegate = x => x * x;
int j = myDelegate(5);

Is there a way in c# to encapsulate a method delegate WITH parameter values? Essentially delay invocation of a fully parametrized method? So you don't have to supply parameter values at invocation time?

For example something like this invalid code:

delegate int del(int i);   
del myDelegate(5) = x => x * x;
int j = myDelegate;

I'm aware the use case isn't immediately obvious. In the case I'm currently looking at, I have a non-deterministic method that I would like the caller to be able to invoke without having to contain or be aware of the parameters the method needs. One way to achieve this would be via creating a class that encapsulates both the parameter values and the method delegate and have that referenced and invoked by the caller. But I'm just curious if there is an alternate, more succinct way.

+1  A: 

You could always wrap one delegate in another. As SLaks mentioned, this is called currying:

Func<int, int> square = i => i * i;
Func<int> squareFive = () => square(5);

int j = squareFive();
Justin Niessner
+11  A: 

This is called currying.

For example:

Action curried = () => myFunc(5);

Or,

Func<int, int, int> multiplier = (x, y) => x * y;
Func<int, int> doubler = x => multiplier(x, 2);
int eight = doubler(4);
SLaks
+1  A: 
Func<int, int> myDelegate = x => x * x;
Func<int> myDelegate5 = () => myDelegate(5);
int j = myDelegate5();
LukeH