Thursday, November 26, 2009

Safe List object from SPWeb in SharePoint 2010


If MOSS 2007, the code to read the list object use to be

SPWeb web;
SPList list = null;
list = web.Lists[“Pages”] }
catch(Exception ex)
// List not found

The reason to have a try-catch was because SharePoint would throw an exception if the list does not exist

Glad to see that in SharePoint 2010, this issue is fixed. The code in SharePoint 2010, would be

SPWeb web;
SPList list = web.Lists.TryGetList(“Pages”)

TryGetList returns the list with the specified title from the list collection, but returns null if its not found. No more more error handling is required