Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I declare a Func Delegate which returns a Func Delegate of the same type?

Tags:

c#

delegates

func

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?

like image 868
Marwie Avatar asked Jan 16 '15 17:01

Marwie


People also ask

Can delegates return type?

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.

When you create a delegate what type of expression can you use instead of using an anonymous method?

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 .

What will happen if a delegate has a non void return type?

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.

What is the return type of a func C#?

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.


1 Answers

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);
like image 191
Lucas Trzesniewski Avatar answered Oct 23 '22 20:10

Lucas Trzesniewski