1

If i make a Stream object to open a text file with OpenFileDialog, in what scope should i close it? In the same scope were i declared it, or inside one of the ifs (to close it just in the case that it opened properly)?.

I leave you the code here so you can tell me...

Stream arch_Usuarios; OpenFileDialog openFileDialog_arch_Usuarios = new OpenFileDialog(); if (openFileDialog_arch_Usuarios.ShowDialog() == DialogResult.OK) { if ((arch_Usuarios = openFileDialog_arch_Usuarios.OpenFile()) != null) { ... } } 

Greetings.

4
  • 5
    Look into using statement. That should solve this problem. Commented Nov 15, 2013 at 13:42
  • 2
    What do you meant by "they didn't open properly" ? Commented Nov 15, 2013 at 13:43
  • 1
    If a stream doesn't open properly, you won't get null or an uninitialized stream, but an exception. Commented Nov 15, 2013 at 13:44
  • Side note: Use .net naming conversions. refrain using Abc_Def style Commented Nov 15, 2013 at 13:44

1 Answer 1

6

If you put those resources in a using statement, you won't have to worry about it. These objects are automatically cleaned up when they go out of scope, regardless of how the code exits, meaning even in the event that exception is thrown.

using(OpenFileDialog openFileDialog_arch_Usuarios = new OpenFileDialog()) { if (openFileDialog_arch_Usuarios.ShowDialog() == DialogResult.OK) { using(Stream arch_Usuarios = openFileDialog_arch_Usuarios.OpenFile()) { ... } } } 

And here's my one pet peeve with using statements. You wind up with ridiculously indented code. Minor complaint, but still annoys me.

Sign up to request clarification or add additional context in comments.

7 Comments

You need to use OpenFileDialog in using statement as well
True. They could all go in using statements. The one thing I don't like about using statements (and this is minor) is the indentation that results. I tend to use them sparingly for that reason.
@SriramSakthivel: I don't think the dialog needs to go in a using, only the stream
@musefan Why? OpenFileDialog uses unmanaged system resource, which has to be disposed.
It could be argued either way. For readability, I prefer to use them sparingly. @musefan, the file dialog will be disposed when it goes out of scope.
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.