So, I need to create a file using the StreamWriter class, write to it and then close it, and I want to put all the potentially inexecutable operations in try blocks; and as the file creation and write operations will be in different try blocks, I can’t initialize the StreamWriter variable (create the file) in one try block and then use it in another. I guess I could declare the StreamWriter variable outside the try blocks and set it to null, then initialize it in a try block, but MSDN says “When inside a try block, only initialize variables that are declared therein; otherwise, an exception can occur before the execution of the block is completed”. What is the best practice for safely declaring, initializing, using a file stream variable (or any variable, for that matter) and then disposing of it? Maybe I should use something instead of StreamWriter? Also, why shouldn’t you initialize a variable in a try block if you hadn’t declared it there?
Thanks.
So, I need to create a file using the StreamWriter class, write to it
Share
The StreamWriter’s lifetime should be managed by a using block.
Your instinct to move the variable declaration outside of the two try blocks is correct if you want to access it from within both. The MSFT guidance is just trying to impress upon you that in that case if you have possible exceptions occurring after declaration but before the try blocks they won’t be caught, but initializing a variable to null will not throw an exception and if you don’t do anything other than that you are fine. (If you were really worried about it though, you could just create a try/catch that encapsulates the variable declaration and also the other try blocks) Personally I am not a fan of a lot of try/catch but that’s a sermon for another day…