1

Would this code cause an SPList object to leak? It's enclosed in a Using statement but that's in a sub routine.

String site = "http://server/sites/site";
foreach (string s in OutputListField(GetList(site, "Documents")))
{
    Response.Output.WriteLine(s + "<br />");
}


protected string[] OutputListField(SPList list)
{            
    if (list == null) throw new ArgumentNullException();

    string[] propertyValue = new string[list.Items.Count];

    int i = 0;
    foreach (SPListItem item in list.Items)
    {
        propertyValue[i] = item["Name"].ToString();   
        i ++;
    }
    return propertyValue;
}


protected SPList GetList(string site, string listname)
{

    SPList list = null;;
    using (SPSite mySite = new SPSite(site))
    {
        using (SPWeb myWeb = mySite.OpenWeb())
        {
            list = myWeb.Lists[listname];
            }
            if (list == null)
            {
                throw new ArgumentNullException();
            }
            return list; **"Would this cause the SPList to leak?"**
        }   
    }
}

4 Answers 4

3

Counting the contents of the item collection can be very slow. Instead use the ItemCount property on the list.

With regards to checking for leaks, have a look at SPDisposeCheck.

1
  • great advice on ItemCount, I was unaware of that property, thanks.
    – Rob
    Jun 29, 2010 at 8:20
3

It won't cause a memory leak but it's not best practice.

Some API calls require SharePoint to have parent SPWeb and SPSite objects initialised. Accessing the list once its parent web object has been closed could cause errors (perhaps not in this exact code).

My opinion is to play it safe and don't risk it.

1

I agree 100% with Alex.

If you really need a method that returns an SPList, I would refactor it to accept the containing SPWeb as a method parameter.

Rewrite the first bit with:

string url = "http://server/sites/site";

using(SPSite site = new SPSite(url))
{
    using (SPWeb web = site.OpenWeb())
    {
        foreach (string s in OutputListField(GetList(web, "Documents")))
        {
            Response.Output.WriteLine(s + "<br />");
        }  
    }
}

and rewrite your GetList() method to the following:

protected SPList GetList(SPWeb web, string listname)
{
    SPList list = web.Lists[listname];
    if (list == null)
    {
      throw new ArgumentNullException();
    }
    return list;
}
1
  • cool! that is much cleaner than my code.
    – Rob
    Jul 2, 2010 at 6:49
0

To the best of my knowledge, this code wont cause a memory leak, but give a shot with the SPDisposeCheck.exe

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

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