Thursday, 7 May 2009

Collapsing multiple using statements

Multiple, nested using statements are extremely common when developing against the SharePoint API to ensure the various objects at work are disposed of correctly:

using (SPSite site = new SPSite ("http://server")){
using (SPWeb web = site.OpenWeb())
{
str = web.Title;
}
}

Under the hood, the CLR transforms both using statements into two try/finally blocks—one nested inside the other—where the relevant object is disposed in each finally block. Handy but these multiple using blocks still leave the code that does all the real work of your application indented far into the page. Add some if statements, loops, or RunWithElevatedPrivileges calls and you’re halfway across.

To clean up ever so slightly, the two using blocks in the example above can actually be combined or stacked with a single block (a single set of braces and a single level of indentation):

using (SPSite site = new SPSite ("http://server"))
using (SPWeb web = site.OpenWeb())
{
str = web.Title;
}

The end result is the same at the MSIL level: two try/finally blocks nested one inside the other (check ildlasm.exe) but you regain one level of indentation.

No comments:

Post a comment

Spam comments will be deleted

Note: only a member of this blog may post a comment.