title: Elegant way to prevent StackOverflow in Recursion
body: <p>I'm trying to port <a href="https://www.burakkanber.com/blog/machine-learning-genetic-algorithms-part-1-javascript/" rel="nofollow noreferrer">this Genetic Algorithm</a>,
  and I made a recursive function for advancing from one generation to another.</p>
  
  <p>However, as I'm new to recursion in C# (and in general), I evidently bumped into StackOverflowException when there were too many generations (more than around 4500).</p>
  
  <p>In order to solve the problem, I made Generation() return a bool, so when the genetic algorithm reachs max fitness (goal), it returns true. Else it returns Generation().</p>
  
  <p>If it's about to overflow (Generation > 4500), it returns false.</p>
  
  <p>Now In Main(), to keep Generation() running until it returns true, I use a while loop, so it will start over the recursion until it completes.</p>
  
  <p>This is way more efficient than doing Task.Run, so I went for this approach.</p>
  
  <p>Is this good practice? Are there any more elegant ways of preventing StackOverflows without sacrificing performance?</p>
  
  <p><strong>Population.cs:</strong></p>
  
  <pre><code>class Population
  {
  
      public int GenerationNumber { get; private set; }
      public int TotalGenerationNumber { get; private set; }
      public const int StackGenerationLimit = 4500;
  
      public Population()
      {
  
          GenerationNumber = 0;
          TotalGenerationNumber = 0;
  
  
      }
      public bool Generation()
      {
          // Work
          // if(HasReachedGoal) return true;
  
          GenerationNumber++;
  
  
          if(GenerationNumber &gt; StackGenerationLimit)
          {
              return false;
          } else
          {
              return Generation();
          }
  
  
      }
  
      public void ResetStack()
      {
          TotalGenerationNumber += GenerationNumber; // I store the total number of generation for information purposes
          GenerationNumber = 0; // Reset the recursion depth value
      }
  
  
  
  
  }
  </code></pre>
  
  <p><strong>Program.cs</strong></p>
  
  <pre><code>class Program
  {
      static void Main(string[] args)
      {
          Population population = new Population();
  
          while (!population.Generation()) // Until it reaches its goal
          {
              population.ResetStack();
          }
  
          Console.WriteLine("End. Generations: " + population.TotalGenerationNumber);
  
  
      }
  }
  </code></pre>