Best practice for nested using statements?

后端 未结 5 1148
情书的邮戳
情书的邮戳 2021-01-17 12:19

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 a

5条回答
  •  醉酒成梦
    2021-01-17 12:54

    Maybe something conventional; best approach for choosing between two in my opinion would be;

    • Using : If you are going to use an instance within a context and need to Dispose it after you are done with it
    • try/finally : If you are expecting any issue and have something to do with the exception, catching it before you Dispose the instance you are using.

    And as other comments / answers state; you don't need instance level variables;

    using (FileStream fileStream = new FileStream("ABC.pdf", FileMode.Create))
    using (Document document = new Document(PageSize.A4, marginLeft, marginRight, marginTop, marginBottom))
    using (PdfWriter pdfWriter = PdfWriter.GetInstance(document, fileStream))
    {
        // # Implementation here seems like a good approach
    }
    

提交回复
热议问题