Kalanamith Kalanamith - 1 year ago 86
C# Question

Best practice for nested using statements?

I have a code block as follows and I'm using 3 nested

using
blocks.

I found that using
try finally
blocks I can avoid this but if there are more than two using statements, what is the best approach?

private FileStream fileStream = null;
private Document document = null;
private PdfWriter pdfWriter = null;

using (fileStream = new FileStream("ABC.pdf", FileMode.Create))
{
using (document = new Document(PageSize.A4, marginLeft, marginRight, marginTop, marginBottom))
{
using (pdfWriter = PdfWriter.GetInstance(document, fileStream))
{
document.AddAuthor(metaInformation["author"]);
document.AddCreator(metaInformation["creator"]);
document.AddKeywords("Report Generation using I Text");
document.AddSubject("Document subject");
document.AddTitle("The document title");
}
}
}

Answer Source

You can remove the nesting indention this way:

using (var fileStream = new FileStream("ABC.pdf", FileMode.Create))
using (var document = new Document(PageSize.A4, marginLeft, marginRight, marginTop, marginBottom))
using (var pdfWriter = PdfWriter.GetInstance(document, fileStream))
{
   // code
}

edit: as Jon Skeet pointed out, you should declare the variables in the using-statement

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download