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?
Yes. A
finallyblock must be preceded by atryblock. Onlycatchis optional. Besides that you should read a bit about scope. Theswvariable you declare in theusingblock is not accessible outside that block.Furthermore the
usingwill dispose theStreamWriter(FileWriteris 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.