简体   繁体   中英

C# list collection loses its value outside of method

I'm new to C# and the ASP.NET framework and can't seem to find an answer as to why the values added to a list collection in one method either disappear or can't be accessed in another method. If I print the contents of the list right after it is created, the values are returned, but the debugger says there's nothing in the list after the list has been created and accessed in a different method.

This is the class that is the datatype for the list:

class Letter
{
    public char Character { get; set; }
    public bool Guessed { get; set; }
}

This is the list being declared (the printing out at the end does work):

private List<Letter> currentWord = new List<Letter>();

This is the method creating the list:

protected void CreateCurrentWordList()
    {
        char[] letterArray = computerChoice.ToCharArray();
        for (int i = 0; i < letterArray.Length; i++)
        {
            currentWord.Add(new Letter { Character = letterArray[i], Guessed = false });
        }
        string displayString = PrintCurrentWord();
        TestLabel.Text = displayString;
    }

And this is the code block in another method that can't access the values inserted into the list or where the list shows up as empty in the debugger:

foreach (Letter letter in currentWord)
            {
                if (letter.Character.ToString() == userGuess)
                {
                    letter.Guessed = true;
                    displayString += letter.Character.ToString();
                }                   
            }

Thanks for any help or direction to another post answering this question.

EDIT: Adding static keyword to list collection declaration seems to have solved the problem. Thanks PiJei!

It could be for many reasons:

  1. You have two or more objects instantiated and one of them has no values in it.
  2. You are using the block code of the method that can't access the values before adding values to the list.
  3. You postback the page losing the data in the list.

I would try storing currentWord in a ViewState["myList"] to see if it has values after some requests.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM