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

前端 未结 5 971
野趣味
野趣味 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:20

    The first is better. It ensures it is disposed even if an exception is thrown, and it correctly handles the case where Create(0) returns null (i.e. it doesn't attempt to call Dispose() on a null instance).

提交回复
热议问题