My code looks like the below. Obviously I can't write 'Ok' because the object has been disposed. I can't do return sw.Clone() because clone doesn't exist. If I don't use a using then at any point between = new and return (like iterating and writing to the object as my example doesn't do) can have an exception and thus not disposing the object.
Am I to define sw outside of a try block and check if it's null then dispose in a catch block? That seems like a bit of excessive work. Is there a better way? Is that the only way?
static void func1()
{
using (var sw = func2())
{
sw.WriteLine("Ok");
}
}
static StringWriter func2()
{
using (var sw = new StringWriter())
{
return sw;
}
}
You may want to reconsider returning a StringWriter. While you may have a few places where you need that extra functionality, it feels to me like plumbing sticking up in the middle of the living room. It shouldn't be part of a public API, and is kinda clunky even in a private one.
With that said, if you need one, don't Close or Dispose it before returning it, and don't use a using block. Use a try/catch block (ie: Dispose in the catch, not the finally clause).