Thursday, June 24, 2010

Object reference not set to an instance of an object at System.Linq.Enumerable.WhereListIterator`1.MoveNext()

Linq query are one of the favourite among the developers, sometimes people get following error in the Linq Query and became clueless.Error will look like following

Object reference not set to an instance of an object at System.Linq.Enumerable.WhereListIterator`1.MoveNext()

For Example we have a query like following
cars = from car in Vehicle.Cars
where car.Make.Contains("BMW")
select car;
we then enumerate through the cars like
foreach (var myCar in cars)
{
//
}
the code starts blowing up in the enumeration with a error Object reference not set to an instance of an object at System.Linq.Enumerable.WhereListIterator`1.MoveNext()
At first instance we may wonder why this is not working looks like the code has no issue. If we look at the query closely we can see the where condition "car.Make.Contains("BMW") " can blow up if the Make is null. So we found the issue next we need to change the query like following
cars = from car in Vehicle.Cars
where ((car.Make != null) && (car.Make.Contains("BMW")))
select car;

Now we are good to go.Stop Googling !!!
Cheers
Shyju Mohan

No comments:

Post a Comment