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

前端 未结 5 995
野趣味
野趣味 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条回答
  •  旧巷少年郎
    2020-12-19 08:02

    The using statement gives you nice syntax plus exception protection. You cannot leave the using statement without calling Dispose (it translates into a finally block with a call to dispose). In your second scenario, if you had an exception between the Create and the Dispose, you would not call dispose directly. Which is not a problem unless you are using unmanaged resources, but if you are, you will leak.

提交回复
热议问题