简体   繁体   中英

Return Type for recursion in c#

Which return type should we use in c#?Is recursion possible using the "void" return type in c#?

I have a function in which return type is a void, but when I call it, it recursively undergoes Infinite looping, so what is better solution for this:

I am using function as stated below:

void A()
{
  //Some code
  A()
}

I think your understanding of recursion needs some sharpening.

Have a closer look at Recursion

Despite the usefulness of recursion, you can easily create a recursive function that never returns a result and cannot reach an endpoint. Such a recursion causes the computer to execute an infinite loop.

Another problem that can occur with recursion is that a recursive function can use all the available resources (such as system memory and stack space). Each time a recursive function calls itself (or calls another function that calls the original function), it uses some resources. These resources are freed when the recursive function exits, but a function that has too many levels of recursion may use all the available resources. When this happens, an exception is thrown.

Your issue here is not the return type. You need to have some rule for the resursion to end, lets say a depth of recustion call, or a number of directories as a max to recurs.

Maybe also have a look at Recursive methods using C#

Every recursive method sequence must be somehow terminated. Often the first part of the recursive method will have a branch that tests for a condition being met. In this way, the recursive methods continue until the result is attained. for example

static int Recursive(int value)
    {       
    if (value >= 10)
    {
        // throw new Exception("End");
        return value;
    }
    return Recursive(value + 1);
    }

There is nothing to do with the return type. if conditions are not supplied your function will go to infinite loop

As you are calling the same function, it is obvious it will go in infinite loop. After a condition is satisfied you need to come out of this loop and that can be achieved by using break keyword.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM