Reputation: 5232
C# keyword Using implements Idisposable which provides a mechanism for releasing unmanaged resources.
Now i was going through this code
string txt = String.Empty;
using (StreamReader sr = new StreamReader(filename)) {
txt = sr.ReadToEnd();
}
and cant stop wondering, why is the keyword Using is used in this code while StreamReader is a Managed resource and it is the responsibility of the garbage collector to free up the objects memory after its scope gets over.
So my question is,
Upvotes: -1
Views: 697
Reputation: 4835
why is the keyword Using is used in this code while StreamReader is a Managed resource
While StreamReader is a managed object it may hold objects inside it which are not allocated on the managed heap. Garbage Collector has no visibility on their allocation and hence cannot clean them up. For the particular case of StreamReader
it internally creates a FileStream
(for your particular case) which internally creates and holds a WIN32 filehandle.
_handle = Win32Native.SafeCreateFile(tempPath, fAccess, share, secAttrs, mode, flagsAndAttributes, IntPtr.Zero);
(Code Reference)
using
is just shorthand for:
try
{
var streamReader = new StreamReader(path);
// code
}
finally
{
streamReader.Dispose();
}
Methods implementing IDisposable
need to implement Dispose
where they get the opportunity to close file handles, sockets, or any such resource that may need manual cleaning.
If one choses to hold a StreamReader
inside a class then that class should implement IDisposable
too, to correctly pass on the Dispose
to the StreamReader
.
So the IDisposable
can be considered as a contract for classes that either hold native objects, or hold objects that implement IDisposable
Upvotes: 1
Reputation: 206
I think this is more of a defensive coding style where I don't want the stream reader object to be used as the file associated with this object has already been read completely using ReadtoEnd function and is being referred by txt.
Upvotes: -5