understand "using" in app code

  • Thread starter Thread starter S Moran
  • Start date Start date
S

S Moran

why would i do this?
using (FileStream fs = File.Create(path))

wouldnt
FileStream fs = File.Create(path)
work fine?
 
In message %[email protected],
S Moran said:
why would i do this?
using (FileStream fs = File.Create(path))

wouldnt
FileStream fs = File.Create(path)
work fine?

As I understand it in the first example,
You would use it like:
using (FileStream fs = File.Create(path))
{
.... Some Code
}

The object fs would be automatically disposed of by the garbage collector
once the code inside the using block had completed.

In the second example, the object would exist until the routine containing
the statement completed, or until you explicitly got rid of it.
 
The following are equivalent:

1.
---

using (FileStream fs = File.Create(path))
{
//work here
}


2.
---

FileStream fs;

try
{
fs = File.Create(path);
//work here
}
finally
{
fs.Dispose();
}

--
Gregory A. Beamer
MVP; MCP: +I, SE, SD, DBA
http://gregorybeamer.spaces.live.com
Co-author: Microsoft Expression Web Bible (upcoming)

************************************************
Think outside the box!
************************************************
 
ChrisM said:
As I understand it in the first example,
You would use it like:
using (FileStream fs = File.Create(path))
{
... Some Code
}

The object fs would be automatically disposed of by the garbage collector
once the code inside the using block had completed.

It's not the garbage collector that calls Dispose, it's the code
generated by the compiler.
In the second example, the object would exist until the routine containing
the statement completed, or until you explicitly got rid of it.

Neither version will "get rid of" the object - that's up to the garbage
collector, which may run a lot later than the end of the routine (or
may be able to collect the object before the routine has finished,
depending on use).

The important thing is that by calling Close or Dispose on a stream,
you release the unmanaged resources (the file handle in this case)
associated with the stream. The "using" statement is good because it
puts a call to Dispose at the end of the block, wrapped in a
try/finally block.
 
Back
Top