4

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();
        }
    }
}
4
  • 5
    What do you think return GenerateNumbers(); does? This is important to know to correct your misunderstanding. Commented Jun 14, 2016 at 14:03
  • 3
    Hint: infinite recursion Commented Jun 14, 2016 at 14:04
  • 7
    use return num; or just numbers = Enumerable.Range(1,10); Commented Jun 14, 2016 at 14:05
  • I see now. It makes sense. Thanks alot! Commented Jun 14, 2016 at 14:09

4 Answers 4

10

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
    }
Sign up to request clarification or add additional context in comments.

Comments

5

A stack overflow is an undesirable condition in which a particular computer program tries to use more memory space than the call stack has available. In programming, the call stack is a buffer that stores requests that need to be handled. http://whatis.techtarget.com/definition/stack-overflow

 static int[] GenerateNumbers()
 {
     int[] num = new int[10] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
     return GenerateNumbers(); //Here is where the problem happens
 }

The problem lies with the return part. You are calling the same function in the same function creating a stack of the same function again and again and... You get the picture.

Change it to

return num;

1 Comment

@Mafii Thank you for the heads up. I have edited the answer.
0

By calling return GenerateNumbers() at the end of your function, you are running that function over and over again infinitely because there is no way to break the recursion, causing the stack overflow. You should instead use return num

Comments

0

This is what you're esentially doing:

void Main() 
{
    FlipPage();
}

void FlipPage()
{
    FlipPage();
}

So like that blond you keep flipping that page in all eternity

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.