When are C# “using” statements most useful?

后端 未结 14 1918
没有蜡笔的小新
没有蜡笔的小新 2021-02-13 05:33

So a using statement automatically calls the dispose method on the object that is being \"used\", when the using block is exited, right?

But when is this necessary/benef

14条回答
  •  逝去的感伤
    2021-02-13 05:58

    It seems very simple to me.

    If a class implements IDisposable, then it is almost asking you to please call Dispose on any instance that you create, as soon as you're done with it. This is the pattern I suggest should be used, whenever such an instance is created:

    using (var instanceName = new DisposableClass())
    {
        // Your code here
    }
    

    It's simple, it's clean, and it works for everything except for WCF proxy classes, which are broken. For those, see http://www.iserviceoriented.com/blog/post/Indisposable+-+WCF+Gotcha+1.aspx.

提交回复
热议问题