Which is better, and when: using statement or calling Dispose() on an IDisposable in C#?

前端 未结 5 988
野趣味
野趣味 2020-12-19 07:36

Suppose I have the following:

using(var ctx = DataContextFactory.Create(0))
{ ... Some code ... }

Why not just do the following and lose a

5条回答
  •  梦毁少年i
    2020-12-19 07:58

    The only place you don't want to use a using block is where the disposable object is scoped outside of the function. In this case, your class should implement IDisposable and dispose of the object in its Dispose().

提交回复
热议问题