TryGetList – SharePoint 2010 Object Model Enhancements

Any developer that worked with WSSv3 found out that there was no “nice and easy” way to check if a SPList existed and handle it accordingly. One of the easiest and most popular methods (no pun intended!) was to handle it with a try catch block. This worked effectively and it was part of every utilities class that was used when working with SharePoint.

SPSite currentSite = SPContext.Current.Site;
SPList mySPList = currentSite.RootWeb.Lists.TryGetList("ListName");


if (mySPList != null)
{
  ...
}

I was not even aware that SharePoint 2010 added a method to handle this automatically until I stumbled upon a TryGetList method within SPWeb.Lists. In SharePoint 2010 you no longer need an extension of any sorts to help handle getting lists, you can just use the TryGetList method and everything else will be taken care of! If the list does not exist then the object will just be null with no exception being thrown. You can check out the full documentation on MSDN here.

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.