0

This is my code:

string data = "...";
var stream = new StreamReader(data);

Is that okay not call the Close() method?

Matan Shahar
  • 3,190
  • 2
  • 20
  • 45
  • It won't leak external resources, if you're talking about `StringReader` (which it seems like you are). See also http://stackoverflow.com/questions/6122013/should-i-close-a-stringreader – Mihai Oct 14 '12 at 09:12
  • 1
    It's always best to be consistent when working with IDisposable objects. See http://msdn.microsoft.com/en-us/library/yh598w02%28v=VS.80%29.aspx - you should consider `using` to avoid memory leaks or keeping unmanaged resources in use. – dash Oct 14 '12 at 09:12

4 Answers4

5

Yes, otherwise you will have a memory leak. Wrap your StreamReader in a using statement so you don't have to worry about cleaning it up e.g.

using (var reader = StreamReader(data))
{
    ...
}
James
  • 80,725
  • 18
  • 167
  • 237
1

Have you actually compiled and run your code?

The StreamReader(string) constructor treats the input as a file name!

Unless this isn't really your code and you meant StringReader, your code is trying to stream the contents of the file name specified in data, which is likely to throw a FileNotFoundException because the file probably doesn't exist. And if it did, you would certainly need to call Close or integrate your code into a using statement to release the file handle.

Adam
  • 15,537
  • 2
  • 42
  • 63
0

You might also want to take a look at this tutorial on msdn:
http://msdn.microsoft.com/en-us/library/aa355056.aspx

which tells you about things you need to be careful with the using statement. Other than that, using is the way to go.

Another pretty good article on codeProject. Worth reading.

woodykiddy
  • 6,074
  • 16
  • 59
  • 100
0

The resource will not be accessable to other processes until your process stops using it so you should close it if you don't need it

yohannist
  • 4,166
  • 3
  • 35
  • 58