C# USING keyword - when and when not to use it?

后端 未结 3 1451

I\'d like to know when i should and shouldn\'t be wrapping things in a USING block.

From what I understand, the compiler translates it into a try/finally, where the

3条回答
  •  佛祖请我去吃肉
    2020-12-05 07:52

    "Are IDisposables not disposed of when they go out of scope?"

    No. If the IDisposable object is finalizable, which is not the same thing, then it will be finalized when it's garbage collected.

    Which might be soon or might be almost never.

    Jeff Richter's C#/CLR book is very good on all this stuff, and the Framework Design Guidelines book is also useful.

    Do I only need to use a USING when my object makes use of Dispose to tidy itself up?

    You can only use 'using' when the object implements IDisposable. The compiler will object if you try to do otherwise.

提交回复
热议问题