Intermittent "Object reference not set to an instance of an object" error when looping through SPListItemCollection

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 Microsoft.SharePoint.SPListItemCollection.EnsureListItemsData()
at Microsoft.SharePoint.SPListItemCollection.Undirty()
at Microsoft.SharePoint.SPBaseCollection.System.Collections.IEnumerable.GetEnumerator()
at System.Linq.Enumerable.d__aa`1.MoveNext()
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.

Advertisement

About Bernado

Based in Australia, I am a freelance SharePoint and Dynamics CRM developer. I love developing innovative solutions that address business and everyday problems. Feel free to contact me if you think I can help you with your SharePoint or CRM implementation.
This entry was posted in SharePoint. Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s