I'd like to write a method which does some work and finally returns another method with the same signature as the original method. The idea is to handle a stream of bytes depending on the previous byte value sequentially without going into a recursion. By calling it like this:
MyDelegate executeMethod = handleFirstByte //What form should be MyDelegate?
foreach (Byte myByte in Bytes)
{
executeMethod = executeMethod(myByte); //does stuff on byte and returns the method to handle the following byte
}
To handover the method I want to assign them to a Func delegate. But I ran into the problem that this results in a recursive declaration without termination...
Func<byte, Func<byte, <Func<byte, etc... >>>
I'm somehow lost here. How could I get around that?
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.
Since a lambda expression is just another way of specifying a delegate, we should be able to rewrite the above sample to use a lambda expression instead of an anonymous delegate. In the preceding example, the lambda expression used is i => i % 2 == 0 .
When the return type is not void as above in my case it is int. Methods with Int return types are added to the delegate instance and will be executed as per the addition sequence but the variable that is holding the return type value will have the value return from the method that is executed at the end.
A Func in C# is a way to define a method in-line that has a return value. There is a similar concept of an Action that doesn't have a return value, but we'll get to that in a sec. The return value's type is always the last generic parameter on the Func 's definition.
You can simply declare a delegate type when the predefined Func<...>
delegates aren't sufficient:
public delegate RecursiveFunc RecursiveFunc(byte input);
And in case you need it, you can use generics too:
public delegate RecursiveFunc<T> RecursiveFunc<T>(T input);
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