質問

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?

役に立ちましたか?

解決

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.

他のヒント

Finally always runs, but your code as it stands is mostly redundant. The code:

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

Is functionally equivalent to

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

StreamWriter's Dispose() method implicitly calls Close(). However this should not be an error because user-defined Finallys run before system-implicit Finallys.

Finally always works, whether or not there is an (uncaught) exception doesn't matter

I believe that when a using is converted to IL - .Net converts a using to a try (of sorts) anyway - And so it will still make sense in this context.

See this article.

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top