Home > OS >  Why is a list inside class list erased when using list.clear()
Why is a list inside class list erased when using list.clear()

Time:12-12

if choices.Clear(); is not use here, the output will be question_1, aaa, bbb, ccc, question_1, aaa, bbb, ccc, 111, 222, 333, question_2, aaa, bbb, ccc, 111, 222, 333

my desired output will be question_1, aaa, bbb, ccc, question_2, 111, 222, 333

that is why I put choices.Clear(); in between because I wanted to erase the previous assigned data in 'choices' list

but when i put choices.Clear(); it deleted the whole thing whichever list that holds choices list

I have a code as below:

Quiz.cs

[System.Serializable]
public class Question
{
    public string question;
    public List<string> choice;
    public int option;
}

GameController.cs

List<Question> question_list = new List<Question>();
List<string> choices = new List<string>();

string question;

void Start()
{
    AssignData("question_1", "aaa", "bbb", "ccc");
    ViewData();

    choices.Clear(); // <- this delete ques.choice inside question_list
    
    AssignData("question_2", "111", "222", "333");
    ViewData();
}

public void AssignData(string question, string choice1, string choice2, string choice3)
{
    choices.Add(choice1);
    choices.Add(choice2);
    choices.Add(choice3);

    question = question;

    var ques = new Question();
    ques.question = question;
    ques.choice = choices;
    ques.option = 2;
    question_list.Add(ques);
}

public void ViewData()
{
    for(int i=0; i < question_list.Count; i  )
    {
        Debug.Log(question_list[i].question);
        foreach(var item in question_list[i].choice)
        {
            Debug.Log(item);
        }
    }
}

CodePudding user response:

Try creating new instance of choices when you assign it to ques.choice property,

ques.choice = new List<string>(choices);

Why do we need it?

  • In your case ques.choice=choices is just referring choices instance. Any operation is done on choices will reflect in ques.choice.
  • To avoid this reference, new List<string>(choices) will create new instance of same list.
  • This will break reference chain and will avoid updating ques.choice after updating choices

.Net Fiddle


From MSDN: Reference types

With reference types, two variables can reference the same object; therefore, operations on one variable can affect the object referenced by the other variable

  • Related