Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

StackoverflowException when filling array

Tags:

c#

I usually spend my time reading and trying to answer the Excel VBA questions but I am trying to learn C# now. Can someone help me understand why I get a StackOverflowException error on the second to last line in my code?
I am trying to fill an array via a method.

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            int[] numbers = GenerateNumbers();
            Console.WriteLine(numbers);
            Console.ReadKey();
        }
        static int[] GenerateNumbers()
        {
            int[] num = new int[10] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
            return GenerateNumbers();
        }
    }
}
like image 228
Brian Avatar asked Dec 06 '22 17:12

Brian


1 Answers

You are confusing the weird VBA way of returning functions with C#. You are returning an infinite recursion, which can be easily fixed by using this:

    static int[] GenerateNumbers()
    {
        int[] num = new int[10] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
        return num; //you don't return the function name but a variable
    }
like image 127
Camilo Terevinto Avatar answered Dec 17 '22 07:12

Camilo Terevinto