Reputation: 4621
Can I return a StreamReader from a method ?
Upvotes: 0
Views: 708
Reputation: 5183
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 ());
}
Upvotes: 1
Reputation: 60902
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.
Upvotes: 5