How do i return a StringWriter When I cant Clone it?

Posted by acidzombie24 on Stack Overflow See other posts from Stack Overflow or by acidzombie24
Published on 2010-05-24T01:17:13Z Indexed on 2010/05/24 1:20 UTC
Read the original article Hit count: 271

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

© Stack Overflow or respective owner

Related posts about .NET

Related posts about exception