I read the msdn article about disposing objects in http://msdn.microsoft.com/en-us/library/ee557362(office.14).aspx
now I’m really confused about this.
consider this example
SPList List = SPContext.Current.Web.Lists["DemoList"];
SPListItem Item = List.GetItemById(ItemID);
is it ok to use this or better to use:
using (SPWeb web = SPContext.Current.Web)
{
SPList List= web.Lists["DemoList"];
SPListItem Item = List.GetItemById(ItemID);
}
or it makes no difference
thanks
You don’t need to dispose of the SPWeb in this case as you didn’t create it. You only need to dispose of an SPWeb object (and SPSite object) if you are responsible for instantiating the object.
So in the following instance you would need to call dispose (or have dispose automatically aclled using the “using” statement) as you were responsible for new-ing up the SPSite..
The “using” statement is equivalant to calling web.Dispose() at the end of the block, but is more readable and the disposal is less likely to be forgotten.
If you are worried about whether you have any undisposed objects in your SharePoint code I strongly recommend using SPDisposeCheck. This tool will analyse your assembly and point out all the places where you could have an undisposed object. It’s great! 🙂