I am trying to write a method to return an instance of itself. The pseudo code is
Func<T,Func<T>> MyFunc<T>(T input)
{
//do some work with input
return MyFunc;
}
seems simple enough. But I am having problem defining the return type. The return type should be a delegate
which takes T as parameter, then returns a function
which takes T as parameter, then returns a function
which takes T as parameter, then returns a function
...recursive definition
I am sure there was some subtle thing that I didn't notice. Can someone point it out for me? Thank you.
The lambda functions do not need a return statement, they always return a single expression.
Lambda expressions, or just "lambdas" for short, were introduced in C# 3.0 as one of the core building blocks of Language Integrated Query (LINQ). They are just a more convenient syntax for using delegates.
delegate: It is the keyword which is used to define the delegate. return_type: It is the type of value returned by the methods which the delegate will be going to call. It can be void. A method must have the same return type as the delegate.
The difference really is that a lambda is a terse way to define a method inside of another expression, while a delegate is an actual object type.
You can do it like this:
delegate F<T> F<T>(T obj);
F<T> MyFunc<T>(T obj)
{
return MyFunc;
}
But it's pretty much useless. The only thing you can really do is something like this, which is weird:
void Main()
{
MyFunc(1)(2)(3)(4);
}
delegate F<T> F<T>(T obj);
F<T> MyFunc<T>(T obj)
{
Console.WriteLine(obj);
return MyFunc;
}
Another way to do it is to make a combinator. Easy peasy, but you can't do it with generics because of that infinite regress. You've got to declare it directly:
delegate D D(D d);
That is, D is a delegate that takes a D and returns a D.
static D MyCombinator(D d)
{
return MyCombinator;
}
A few more thoughts on combinators in C# here:
http://blogs.msdn.com/b/ericlippert/archive/2006/06/23/standard-generic-delegate-types-part-two.aspx
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With