Method returns an IDisposable - Should I dispose of the result, even if it's not assigned to anything?

前端 未结 4 1997
轻奢々
轻奢々 2021-01-13 05:08

This seems like a fairly straightforward question, but I couldn\'t find this particular use-case after some searching around.

Suppose I have a simple method that,

4条回答
  •  梦谈多话
    2021-01-13 05:49

    When you call any method that returns something, an instance of that something is being created. Just because you're not actually capturing it, doesn't make it any less "there". Therefore, in the case of an IDisposable object, the object is being created by the method you're calling in spite of the fact that you're doing nothing with it. So yes, you still need to dispose of it somehow. The first approach with the using statement seems like it should work.

提交回复
热议问题