0

I have this code :

IList<MyObject> myObjects = new List<MyObject>();
if (param != null)
{
    myObjects = (from ... LINQ1 ...).ToList();
}
else
{
    myObjects = (from ... LINQ2 ...).ToList();
}

foreach (MyObject myObject in myObjects)
{
}

when the foreach start, I get a System.NullReferenceException. Why? And how can I fix it? Looks strange...

markzzz
  • 47,390
  • 120
  • 299
  • 507

1 Answers1

1

Your object is being overwritten by one of the LINQ queries which is most likely returning a null value.

Also is myObjects meant to be an IList<MyObject> or List<MyObject> ?

ChrisBD
  • 9,104
  • 3
  • 22
  • 35
  • How? "...).ToList();" is supposed to return a list, even if empty. – TomTom Feb 06 '12 at 11:59
  • @TomTom, yes but it is possible to write a linq query that returns a null ref exception, because of something in the query, the To List is just enumerating through the items and executing the expression – Ben Robinson Feb 06 '12 at 12:03
  • Yes, that is possible- that the not shown part throws a null reference WHEN EVALUATING. – TomTom Feb 06 '12 at 12:10
  • @TomTom, are you saying that .ToList() on a null value is supposed to return an empty list? – Davin Tryon Feb 06 '12 at 12:10
  • 1
    No, i said that ToList always returns a list, even when no element is in teh query. So, the result will never be a null. BUT: as Ben said, it is possible something in the query throws the exception when evaluating. – TomTom Feb 06 '12 at 12:11