6

How to create a fully delegated method in C #?

 2 years ago
source link: https://www.codesd.com/item/how-to-create-a-fully-delegated-method-in-c.html
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

How to create a fully delegated method in C #?

advertisements

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.


This is called currying.

For example:

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

Func<int, int, int> multiplier = (x, y) => x * y;
Func<int, int> doubler = x => multiplier(x, 2);
int eight = doubler(4);


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK