Today I ran into an issue where I intermitently get the following error when attempting to loop through a SPListItemCollection in a foreach loop:
Object reference not set to an instance of an object. at Microsoft.SharePoint.Library.SPRequest.SetVar(String bstrUrl, String bstrName, String bstrValue)
at System.Collections.Generic.List`1..ctor(IEnumerable`1 collection)
at System.Linq.Enumerable.ToList[TSource](IEnumerable`1 source)
at CAPS.Bll.Repositories.SharePointListRepositoryBase.GetItemsByQuery(SPQuery query)
I was looping through a collection that was returned using a CAML search. The error would occur after the 2nd or 3rd time running the same code.
It turned out that it was because my SPWeb object was being held in a static variable (it was an app page, not a console app), and the SPList was being accessed from this SPWeb. Changing the SPWeb to instance variable resolved the problem.
I think it’s probably safer to stay away from static variables in SharePoint dev, particularly if the code is going to run in a web context.