user7275921
user7275921

Reputation:

I have get an error when using a function from a class

I have created a Hangman game. But all the code was in the GUI. I have been reading a lot of programming books and I want to use functions and really program object orientated instead of putting everything in the GUI. So I tried creating a function that generates a random word but it doesn't work. It throws an error: An unhandled exception of type 'System.StackOverflowException' occurred in mscorlib.dll.

class GetSecretWord
{
    public static string GetWord()
    {
        string unsortedwords = "master,bother,bucket,legend,method";
        List<string> sortedwords = unsortedwords.Split(',').ToList();

        int index = new Random().Next(sortedwords.Count);
        string secretWord = sortedwords[index];

        return GetWord();
    }
}

What am I doing wrong?

Also, in my Form code:

 private void btn_Play_Click(object sender, EventArgs e)
    {
        string theSecretWord = GetSecretWord.GetWord();
        MessageBox.Show(theSecretWord);
    }

I use a messagebox to test if it works but it doesn't...

Upvotes: 0

Views: 53

Answers (1)

John Koerner
John Koerner

Reputation: 38079

Change your return to return secretWord

 public static string GetWord()
 {
    string unsortedwords = "master,bother,bucket,legend,method";
    List<string> sortedwords = unsortedwords.Split(',').ToList();

    int index = new Random().Next(sortedwords.Count);
    string secretWord = sortedwords[index];

    return secretWord;
}

Right now you are recursively calling the function which is causing the stack overflow exception.

Upvotes: 2

Related Questions