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;
}
}