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"); } } }
try-finallyblock. So It really depends how you are planning to replace your current structure with atry-finally. A singletry/finallyor multipletry/finallyfor each using blockusingstatements they'll be disposed (and therefore probably useless) anyway - could you make them local variables instead, declared in theusingstatements?newmight fail but it would throw an exception. Instantiating usingClass.GetInstance()static methods might fail but return null. The code ought to check - and recover - in either case.