Simple Pleasures in SP 2010: TryGetList method

How many times has this happened to you?

SPSite site = new SPSite("url");
SPWeb web = site.OpenWeb();
SPList list = web.Lists["ListName"];
ERROR!!!

...because, of course, that list happens not to exist!  Have you ever wished for a better approach than either "Try...Catch" or "loop through the whole mess"?

You just got your wish.

SharePoint 2010 includes a brand-new method on the SPListCollection, called TryGetList.  This method returns a list if successful, but if not, it returns -- get this -- a null value!  No more clumsy extra logic blocks every time you need to do something simple like grabbing a list.  It's not rocket science, but the great innovations rarely are.

No Comments