Search code examples
c#usingfinallyresource-cleanup

Finally block on Using - Does it fire as in other contexts of Finally?


In some code I routinely work with (and have written a few times), code like the following has been used:

using (StreamWriter sw = new FileWriter(".\SomeFile.txt"))
{
    // Perform file IO here...
}
finally
{
    sw.Close();
}

I'm familiar with try/catch/finally in C#...I know that context of finally works. When I performed a google search on the terms "Finally Using", I could find no relevant matches.

Does this context of Finally work as I'm thinking, where upon the final command of the Using statement, the contents of the Finally block get executed? Or do I (and the code base I'm working with) have this all wrong; is Finally restricted to Try/Catch?


Solution

  • is Finally restricted to Try/Catch?

    Yes. A finally block must be preceded by a try block. Only catch is optional. Besides that you should read a bit about scope. The sw variable you declare in the using block is not accessible outside that block.

    Furthermore the using will dispose the StreamWriter (FileWriter is from Java ;-) as soon as the block goes out of scope (i.e. when the last instruction in that block is executed) so you don't have to discard or Close it manually.