0

This is a pretty common technique in JavaScript but I want to make sure I can do this in C#.

I'm in function DoSomething() and during the execution of a call, I need to call the same function with a different value. See below:

public bool DoSomething(int id)
{
    if(id < 100)
    {
         // Some logic here
         var someValue = id + 50;
         var outcome = DoSomething(someValue);

         // Some more logic here
    }
    else
    {
        // Some other logic here
    }
}

I see no reason why I couldn't do the above but want to see if this is a bad practice in C#.

Lance U. Matthews
  • 15,725
  • 6
  • 48
  • 68
Sam
  • 26,817
  • 58
  • 206
  • 383
  • How is recursion a bad practice ?, but id say using `var` is, unless you dont know what the type will be ;) – WilomGfx Oct 21 '17 at 20:50
  • 3
    It's a simple recursion, it's perfectly correct. – Bidou Oct 21 '17 at 20:50
  • 2
    @Ussually recursion is a useful technique for making code terse and comprehensible. However, it is less performant and breeds stack overflow exceptions in non tail call optimized languages. Carefully scrutinize your use case when choosing between recursive and iterative functions. – Roxy'Pro Oct 21 '17 at 20:52

2 Answers2

1

This concept is know as recursion and it is not limited to JavaScript. It's actually a pretty widely know technique and is actually replacing loops in some languages such as scheme.

It is valid to call a function from within itself in C# as well. Just make sure you have a terminating condition since you have a limit on the stack. Since each function call will push another item to the call stack you may end up having what is called a stack overflow

ArchiFloyd
  • 1,274
  • 13
  • 20
1

This technique is called Recursion.

Recursion in computer science is a method where the solution to a problem depends on solutions to smaller instances of the same problem (as opposed to iteration).

Most computer programming languages support recursion by allowing a function to call itself within the program text.

It's not bad practice, but whether or not it's correct for you depends on your use-case. For instance, some problems are easier to express via recursive calls, rather than iterative loops.

While recursion generally means another function invocation (therefore the current execution context being pushed into the call stack - and so on), some languages perform a tail call optimisation that avoids the performance penalty altogether.

As mentioned in other answers, make sure that you have a proper termination condition inside the recursion.

Gerardo Cauich
  • 559
  • 5
  • 20