Search code examples
c#.netusing-statement

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");
        }
    }
}

Solution

  • You can remove the indention and curly brackets 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
    }