Should “Dispose” only be used for types containing unmanaged resources?

后端 未结 15 1668
执笔经年
执笔经年 2020-12-05 01:41

I was having a discussion with a colleague recently about the value of Dispose and types that implement IDisposable.

I think there is value

15条回答
  •  猫巷女王i
    2020-12-05 02:01

    While there are good answers to this already, I just wanted to make something explicit.

    There are three cases for implementing IDisposable:

    1. You are using unmanaged resources directly. This typically involves retrieving an IntPrt or some other form of handle from a P/Invoke call that has to be released by a different P/Invoke call
    2. You are using other IDisposable objects and need to be responsible for their disposition
    3. You have some other need of or use for it, including the convenience of the using block.

    While I might be a bit biased, you should really read (and show your colleague) the StackOverflow Wiki on IDisposable.

提交回复
热议问题