Tell me more ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

The issue is, every entry in my list becomes a copy of the entry that was just added.

So basically, if I end up with 10 objects in my list (10 lines in the text file), all 10 objects in the list will become a copy of the 10th object. This is true at any point during the loop, if I stop on the 6th iteration, all 5 previous entries will now be a copy of the 6th line I am adding.. this is my loop:

StreamReader lolz = new StreamReader("test.txt");

while (!lolz.EndOfStream)
{
    string line = lolz.ReadLine();
    string[] lines = line.Split('|');
    {
        tasksList.Add(new TaskList(lines[0], lines[1], lines[2], lines[3], lines[4], lines[5], lines[6]));
    }
}

Makes 0 sense to me.

share|improve this question
2  
what it tasksList ? – Mr. May 31 at 22:54
1  
Is TaskList possibly a static object or are the member variables static? – CharlesC May 31 at 22:55
List<TaskList> tasksList = new List<TaskList>(); TaskList is my class – Yelnik May 31 at 22:55
3  
why do you have the curly braces around the tasksList.Add call? – Roman Royter May 31 at 22:56
2  
CharlesC got the right answer, my class variables were all static. Thanks a lot – Yelnik May 31 at 23:00

1 Answer

Try to remove the braces, instead of the

string[] lines = line.Split('|');
{
    tasksList.Add(new TaskList(lines[0], lines[1], lines[2], lines[3], lines[4], lines[5], lines[6]));
}

just

string line = lolz.ReadLine();
string[] lines = line.Split('|');
tasksList.Add(new TaskList(lines[0], lines[1], lines[2], lines[3], lines[4], lines[5], lines[6]));

It seems you are getting the last object by reference, you shoudl check if you aren't using an static class or static members, maybe you should post the entire code to properly answer your question...

It should be used something like this:

using(StreamReader lolz = new StreamReader("test.txt"))
{
    string line;
    string[] lines;
    while ((line = lolz .ReadLine()) != null)
    {
        lines = line.Split('|');
        tasksList.Add(new TaskList(lines[0], lines[1], lines[2], lines[3], lines[4], lines[5], lines[6]));
    }
}
share|improve this answer
How does this answer the question? – I4V May 31 at 22:57
I updated my answer – Mr. May 31 at 23:02
Thanks for posting, but it was static class variables that was my issue – Yelnik May 31 at 23:05
if any of these answers resolve your question, post your answer and check it as the correct answer – Mr. May 31 at 23:07
I'm presently unable to answer my own question after such a short amount of time. – Yelnik May 31 at 23:08

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.