Take the 2-minute tour ×
SharePoint Stack Exchange is a question and answer site for SharePoint enthusiasts. It's 100% free, no registration required.

Will using a SPList object derived from a disposed .OpenWeb() cause errors?

SPList list = null;

using (SPWeb web = SPContext.Current.Site.OpenWeb("/myweb")){
    list = web.Lists["Awesome Name"];
}

SPListItemCollection items = list.Items;
share|improve this question
add comment

1 Answer

up vote 2 down vote accepted

No, there will not be an error. I commonly use this design pattern to keep my using blocks small.

SPList list;

using (SPWeb web = SPContext.Current.Site.OpenWeb("myweb"))
{
    list = web.GetList("/myweb/Lists/Awesome Name");
}

SPListItemCollection items = list.Items;

If you are updating an SPListItem in a manner that requires SPWeb.AllowUnsafeUpdates = true; though, you will need to maintain the reference to the SPWeb (IE: do all the work in the using block.)

For more information about when you would need to set the AllowUnsafeUpdates property, see Hristo Pavlov's What you need to know about AllowUnsafeUpdates. It's the best explanation I've found about it.

I do this a lot so I don't have so many nested blocks in my code. It makes it a lot cleaner. Once you retrieve a list it's stored in memory. The same is true if you use the list only within your using block. If something gets changed between the time you load the list and the time you request a value (from an item for instance), the value you get is the value that was present when you loaded the list in the first place.

This is also why if you're only getting a couple lists you should use SPWeb.GetList() instead of SPWeb.Lists[index]. SPWeb.Lists loads all lists in the web on the first call. GetList() makes a database call each time, but if there are a lot of lists in the web you're loading a lot less into memory. It's a trade off.

share|improve this answer
    
But would this cause errors in the logs? –  iambriansreed Dec 20 '12 at 21:55
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.