How do i return a StringWriter When I cant Clone it?
- by acidzombie24
My code looks like the below. Obviously i cant write 'ok' because the object has been disposed. I cant do return sw.Clone() bc clone doesnt exist. If i dont use a using then at any point between = new and return (like iterating and writing to the object as my example doesnt do) can have an exception and thus not disposing the object.
Am i to define sw outside of a try block and check if its 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;
}
}