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

Categories

0 votes
676 views
in Technique[技术] by (71.8m points)

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

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

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

1 Answer

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...