Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

Suppose I have the following:

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

Why not just do the following and lose a couple of curly braces?:

var ctx = DataContextFactory.Create(0);
ctx.Dispose();

Thanks for the advice!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
677 views
Welcome To Ask or Share your Answers For Others

1 Answer

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).


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...