Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I return a delegate function or a lambda expression in c#?

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.

like image 976
Wei Ma Avatar asked Apr 28 '11 04:04

Wei Ma


People also ask

Can you return a lambda function?

The lambda functions do not need a return statement, they always return a single expression.

Is lambda expression a delegate?

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.

What is the return type of delegate?

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.

What is the difference between lambda expression and 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.


2 Answers

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;
}
like image 162
porges Avatar answered Oct 02 '22 12:10

porges


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

like image 37
Eric Lippert Avatar answered Oct 02 '22 12:10

Eric Lippert