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");
}
}
}
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 toDispose
it after you are done with ittry/finally
: If you are expecting any issue and have something to do with the exception, catching it before youDispose
the instance you are using.And as other comments / answers state; you don't need instance level variables;
A little less verbose way to avoid the indenting:
As Jon Skeet pointed out, there is no need for these variables to be instance variables, as they are disposed after the
using
blocks anyway.You can use local variables as shown in the code above instead.
You can remove the indention and curly brackets this way:
In a single method where you don't need to process or change data; the option suggested by Jan Sommer would be my choice. However, in some circumstances the DisposableList is useful. Particularly, if you have many disposable fields that all need to be disposed of (in which case you cannot use using).
Requires you to remember to add the item to the list. (Although you could also say you have to remember to use using.) Aborts the disposal process if one of the disposes methods throws, leaving the remaining items un-disposed.
Now catch any exceptions from the Dispose calls and will throw a new AggregateException after going through all the items. I've added a helper Add method that allows a simpler usage:
now on C# 8 you have using declarations