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?
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.
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.
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.
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.
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; };
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