TakLee
TakLee

Reputation: 3

Foreach to for List objects

foreach (Question question in Holder.Questions)
{
 //...
}

Holder.cs: Holder containts a list of Question objects

public List<Question> Questions{ get; set; }

Question.cs: The Question class holds several attributes such as name, date, etc...

The problem with the foreach i am adding for every question, but i want to add something seperate to a question.

How would i be able to acces the question object in the following class? The holder is already filled up with values of the current holder object.

In other words how do i work with the question. .... without the foreach loop? Cause i am getting the same error all the time that question is actually empty or null (object not set on a reference, ....)

Not really sure how to acces this question. without the foreach loop in this context! Some examples would prove very handy! Thanks.

Upvotes: 0

Views: 592

Answers (2)

asawyer
asawyer

Reputation: 17818

In the constructor of the Holder class make sure to initalize the Questions list object.

this.Questions = new List<Questions>();

In addition you will need to insert Question objects into the List to have something to access.

this.Questions.Add(new Question());

I think you may be trying to access the list like you would an array, which is incorrect.

Edit - Based on your code changes, I think your saying that each time you add a new question, your xml file gets a list of all existing questions each time, with the new question appended to the end, so something like:

In Q1 Out Q1

In Q2 Out Q1 Q1 Q2

In Q3 Out Q1 Q1 Q2 Q1 Q2 Q3

If that's correct, you'll need to change how your file i/o works. You want to create a new xml document, not append to the existing.

Upvotes: 2

David
David

Reputation: 219117

It's unclear what you're asking, but I can at least address the error of the object reference.

List<> is a reference type, and reference types are by default null. So this:

public List<Question> Questions{ get; set; }

will default to null when the class is instantiated. For reference types in your class members to have a default value, you'll need to instantiate them in your constructor:

public Holder()
{
    this.Questions = new List<Question>();
}

Upvotes: 0

Related Questions