tags:

views:

45

answers:

2

Can I return a StreamReader from a method ?

+5  A: 

Yes, of course. It's not a great idea, though - you're creating the StreamReader in one method, and closing it in another. It's better practice to create and close the reader in one method.

Michael Petrotta
Not necessarily a bad idea at all depending on the context. Many methods in the framework exist for the sole purpose of creating disposable resources that the caller is responsible for releasing. Not least of which is File.OpenText, WebResponse.GetResponseStream, Control.CreateGraphics etc.
Josh Einstein
@Josh: I take your point - it's widely done. I still think it's better practice to keep disposal near creation - less chance that you'll forget to dispose it properly.
Michael Petrotta
+1  A: 

Sure. Using normal IDispose semantics, here is how it would look:

  StreamReader MakeStreamReader () {
     return new StreamReader ("somefile.txt");
  }

  void Caller () {
     using (StreamReader r = MakeStreamReader ()) 
        Console.WriteLine (r.ReadToEnd ());
  }
Tarydon