开发者

How do I return a StringWriter When I can't Clone it?

开发者 https://www.devze.com 2022-12-31 03:58 出处:网络
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 poin

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 开发者_Go百科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).


Create a class with the func1 and func2 methods, make that IDisposable, initialize a StringWriter in the constructor, and Dispose of it in your class's Dispose method.

This assumes you're writing to the StringWriter in more than one method.


Get rid of the second using block. Just do

StringWriter sw = new StringWriter();
return sw;

The StringWriter gets disposed if you're defining it in a using block.


FYI: The implementation of StringWriter's close calls the Dispose method passing a true value. Why not just return the second sw to the calling method and call close which will the equivalent.


I'm going to assume this is a general question about returning objects which implement IDisposable, and not a question about func1 and func2.

Use a using block around anything implementing IDisposable if you

  1. Create it and
  2. No longer need it when your method returns

In your case, you are creating it, but it needs to still exist after your method returns. In this case, don't use a using block in the method that creates the object. It then becomes the responsibility of the caller to dispose of the object, which I see it already does.

0

精彩评论

暂无评论...
验证码 换一张
取 消