Since the overhead of having an extra try
/finally
is virtually zero, there is no difference if the compiler combines two blocks in one or keeps them separate. Your translated code would have a single try
-catch
embedded inside two layers of try
-finally
, which are virtually free in terms of performance.
Converting the using
code manually has a different implication - the visibility of variables is different. Your translation of nested using
statements leaves stream
and reader
variables accessible after the block. They refer to a closed stream and a closed reader. Regular using
, on the other hand, keeps its variables inside its scope, as if an additional pair of curly braces were placed around the whole block:
{ // <<==
FileStream stream = null;
BinaryReader reader = null;
try {
stream = new FileStream(filePath, FileMode.Open);
reader = new BinaryReader(stream)
// do my stuff
} finally {
if (stream != null)
stream.Close();
if (reader != null)
reader.Close();
}
} // <<==
using
is better in this way, because it lets you avoid an extra level of nesting while keeping its variable in local scope. Moreover, you could reduce the level of nesting in your source by placing two consecutive using
blocks together at the same level of indentation, with no curly braces:
using (FileStream stream = new FileStream(filePath, FileMode.Open))
using (BinaryReader reader = new BinaryReader(stream)) {
a try/catch around my actual code...
}