-4

I have a List<> declared, which is accessable in the whole class

List<article> data;

Now I'm using a method to fill the List<>:

StreamReader sr = new StreamReader(filePath);

while (!sr.EndOfStream)
{
    string[] Line = sr.ReadLine().Split(';');

    article newArticle = new article();
    newArticle.articleNumber = Line[0];
    newArticle.description = Line[1];
    newArticle.articleId = Line[2];
    try
    {
        data.Add(newArticle);
    }
    catch(NullReferenceException ex)
    {
        // Nothing to do here
    }
} 

Each time, the loop repeats, the newArticle-Object contains all his elements, so it is definetely not null. But it doesn't add to the data-List<>. What am I missing?

Sayse
  • 42,633
  • 14
  • 77
  • 146
Marcel
  • 917
  • 3
  • 19
  • 48
  • 3
    how about the `data`? are you initializing the list before calling `Add` method? and why are you swallowing NullReferenceException ? – Selman Genç Feb 27 '15 at 08:58
  • How often does it get in the `catch` block? – Patrick Hofman Feb 27 '15 at 08:58
  • The `newArticle` may not be null, but the `data` list of articles definitely is – Sayse Feb 27 '15 at 08:58
  • 1
    What they are saying is do: List
    data = new List
    ();
    – Paul Zahra Feb 27 '15 at 08:59
  • ahh.. damn.. that's definetely not my day – Marcel Feb 27 '15 at 09:02
  • 3
    Why are people down voting this question with such ferocity? @Marcel has described the problem, he's posted his code and is just unclear about the response he is seeing in his debugger. A search on his part would possibly have returned a solution, but from the question it appears he wasn't sure of what was causing the issue. – Wizard Feb 27 '15 at 09:07
  • 1
    @Bara'thorn: Him catching a `NullReferenceException` clearly does show he knows what happened. A simple search on it does reveal the actual reason. Instead of ignoring it by putting an empty `catch` he could have fixed the issue. Also, the downvote button gives more reasons to downvote. – Patrick Hofman Feb 27 '15 at 09:08
  • can you please tell use on which line the exception happens? @Marcel – Hamid Pourjam Feb 27 '15 at 09:15
  • Can you post some more code? we would like to focus more on "data" variable – User2012384 Feb 27 '15 at 09:18

1 Answers1

5

In order to add items to the list, you must first initialise it.

Replace:

List<article> data;

with:

List<article> data = new List<article>();
Wizard
  • 1,142
  • 3
  • 16
  • 36