Barry Dysert
Barry Dysert

Reputation: 695

How to populate a List that's within a class in C#?

I'm trying to understand nested types, but even after checking several sites I still don't get it. I have a List that's in a class. I don't see how I can add new items to the List because when I try, it overwrites the existing items with my new ones. Can someone please tell me what I'm doing wrong?

class Program
{
    static void Main(string[] args)
    {
        Master master = new Master();
        master.Username = "Barry";

        Quiz quiz = new Quiz();
        quiz.QuizID = "quiz ID";
        master.quiz = quiz;

        Answers answers = new Answers();
        answers.Answer1 = "answer 1";
        answers.Answer2 = "answer 2";
        answers.Answer3 = "answer 3";
        master.quiz.answers.Add(answers);
        answers.Answer1 = "answer 11";
        answers.Answer2 = "answer 22";
        answers.Answer3 = "answer 33";
        master.quiz.answers.Add(answers);
    }
}

public class Answers
{
    public string Answer1 { get; set; }
    public string Answer2 { get; set; }
    public string Answer3 { get; set; }
}

public class Quiz
{
    public string QuizID { get; set; }
    public List<Answers> answers = new List<Answers>();
}

public class Master
{
    public string Username { get; set; }
    public Quiz quiz { get; set; }
}

When I do the second .Add and then check what's in master.quiz.answers it shows two entries, but they're both the 11, 22, 33 values as if the second .Add overwrote the data that was already in the list.

Thanks.

Upvotes: 1

Views: 55

Answers (3)

shoushouleb86
shoushouleb86

Reputation: 43

Because you are updating the same object. use

 answers = new Answers();

after adding the object to the list

Upvotes: 2

Jeremy Thompson
Jeremy Thompson

Reputation: 65534

Try instantiating the answer object again before adding it to the quiz for the second time.

answers = new Answers();

Upvotes: 2

Ousmane D.
Ousmane D.

Reputation: 56393

You'll need to construct two distinct objects with the new operator.

i.e.

Answers answers = new Answers();
        answers.Answer1 = "answer 1";
        answers.Answer2 = "answer 2";
        answers.Answer3 = "answer 3";
        master.quiz.answers.Add(answers);

Answers anotherAnswer = new Answers(); // construct a new object here
        anotherAnswer.Answer1 = "answer 11";
        anotherAnswer.Answer2 = "answer 22";
        anotherAnswer.Answer3 = "answer 33";
        master.quiz.answers.Add(anotherAnswer);

As an aside, you can make this a little bit cleaner with object initializer syntax:

Answers answers = new Answers
{
      Answer1 = "answer 1",
      Answer2 = "answer 2",
      Answer3 = "answer 3"
};
master.quiz.answers.Add(answers);

Answers anotherAnswer = new Answers
{
      Answer1 = "answer 11",
      Answer2 = "answer 22",
      Answer3 = "answer 33"
}; 
master.quiz.answers.Add(anotherAnswer);

Upvotes: 3

Related Questions