Arno 2501
Arno 2501

Reputation: 9407

Null Reference Exception while Iterating over a List<T>

I'm getting a null exception while iterating over a collection of non nullable objects.

List<ReconFact> facts = new List<ReconFact>();
// ...populating facts 

int count = 0;

foreach (var fact in facts)
{
  Console.WriteLine(++count);
  try
  {
    context = AddToContext(context, fact, count, 100, true);
  }
  catch (Exception e)
  {
    Console.WriteLine(e.Message); // Null Exception Raised at some point
  }
}

How is that possible ? I didn't know that iterating over a list could provide null elements is that a normal behaviour ? Is it possible to add a null item when the list is populated ?

Upvotes: 1

Views: 1255

Answers (3)

RaOne
RaOne

Reputation: 29

I think the problem is in your logic. You just initialize the list of Recontent named fact. So all time its count is 0. Please check that.

Upvotes: 0

Tim Schmelter
Tim Schmelter

Reputation: 460208

Yes, it's possible to add null to a List<T> where T is a reference type. Nothing prevents someone from:

List<ReconFact> facts = new List<ReconFact>();
facts.Add(null);

You could simply check that first:

foreach (var fact in facts.Where(f => f != null))
// ...

Upvotes: 4

Medinoc
Medinoc

Reputation: 6608

Yes, a List can contain nulls, so can arrays and several other collections. It won't break the iterating itself, but it will break any code inside the { } that relies on the element not being null.

List<String> s = new List<String>();
s.Add("foo");
s.Add(null);
s.Add("bar");

Edit: Wait, what do you mean by "non-nullable objects"?

Upvotes: 2

Related Questions