Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create a fully parameterized method delegate in C#?

Tags:

c#

.net

delegates

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.

like image 377
Adam Flynn Avatar asked Dec 10 '22 13:12

Adam Flynn


1 Answers

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);
like image 58
SLaks Avatar answered Dec 31 '22 06:12

SLaks