I\'m a c++ developer having used signals & slots in c++ which to me seems to be analogous to delegates in c#. I\'ve found myself at a loss in searching for the functiona
In C# we do something like this:
class Program {
static Action Curry(Action action, T parameter) {
return () => action(parameter);
}
static void Foo(int i) {
Console.WriteLine("Value: {0}", i);
}
static void Main(string[] args) {
Action curried = Curry(Foo, 5);
curried();
}
}
Clearly the method Foo
corresponds to your method Foo
, just with the appropriate calls to Console.WriteLine
instead of std::cout
.
Next, we declare a method Curry
that accepts an Action
and returns an Action
. In general, an Action
is a delegate that accepts a single parameter of type T
and returns void
. In particular, Foo
is an Action
because it accepts one parameter of type int
and returns void
. As for the return type of Curry
, it is declared as an Action
. An Action
is a delegate the has no parameters and returns void
.
The definition of Curry
is rather interesting. We are defining an action using a lambda expression which is a very special form of an anonymous delegate. Effectively
() => action(parameter)
says that the void
parameter is mapped to action
evaluated at parameter
.
Finally, in Main
we are declaring an instance of Action
named curried
that is the result of applying Curry
to Foo
with the parameter 5
. This plays the same role as bind(fun_ptr(foo), 5)
in your C++ example.
Lastly, we invoke the newly formed delegate curried
via the syntax curried()
. This is like someCallback()
in your example.
The fancy term for this is currying.
As a more interesting example, consider the following:
class Program {
static Func Curry(
Func func,
TArg arg1
) {
return arg => func(arg1, arg);
}
static int Add(int x, int y) {
return x + y;
}
static void Main(string[] args) {
Func addFive = Curry(Add, 5);
Console.WriteLine(addFive(7));
}
}
Here we are declaring a method Curry
that accepts a delegate (Func
that accepts two parameters of the same type TArg
and returns a value of some other type TResult
and a parameter of type TArg
and returns a delegate that accepts a single parameter of type TArg
and returns a value of type TResult
(Func
).
Then, as a test we declare a method Add
that accepts two parameters of type int
and returns a parameter of type int
(a Func
). Then in Main
we instantiate a new delegate named addFive
that acts like a method that adds five to its input parameter. Thus
Console.WriteLine(addFive(7));
prints 12
on the console.