Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can an anonymous method in C# call itself?

I have the following code:

class myClass { private delegate string myDelegate(Object bj);  protected void method()    {    myDelegate build = delegate(Object bj)                 {                     var letters= string.Empty;                     if (someCondition)                         return build(some_obj); //This line seems to choke the compiler                     else string.Empty;                  };    ......    } } 

Is there another way to set up an anonymous method in C# such that it can call itself?

like image 832
Matt Avatar asked Jul 30 '09 19:07

Matt


People also ask

What is anonymous function in C?

Anonymous functions are often arguments being passed to higher-order functions or used for constructing the result of a higher-order function that needs to return a function. If the function is only used once, or a limited number of times, an anonymous function may be syntactically lighter than using a named function.

What is anonymous method in C sharp?

Anonymous methods provide a technique to pass a code block as a delegate parameter. Anonymous methods are the methods without a name, just the body. You need not specify the return type in an anonymous method; it is inferred from the return statement inside the method body.

Where are anonymous methods used?

An anonymous method can be used anywhere. A delegate is used and is defined in line, without a method name with the optional parameters and a method body. The scope of the parameters of an anonymous method is the anonymous-method-block. An anonymous method can use generic parameter types like any other method.

Can an anonymous function return a value?

An anonymous method can return a value. The value is returned by use of the return statement. The type of the return value must be compatible with the return type specified by the delegate. In this version, the value of sum is returned by the code block that is associated with the count delegate instance.


1 Answers

You can break it down into two statements and use the magic of captured variables to achieve the recursion effect:

myDelegate build = null; build = delegate(Object bj)         {            var letters= string.Empty;            if (someCondition)                return build(some_obj);                                        else string.Empty;         }; 
like image 186
mmx Avatar answered Oct 14 '22 09:10

mmx