What is the difference between the following two snippets of code:
using (Object o = new Object())
{
// Do something
}
and
{
Object o = new Object();
// Do something
}
I have started using using a lot more but I am curious as to what the actually benefits are as compared to scoping objects.
Edit: Useful tidbits I took from this:
Jon Skeet:
Note that this does not force garbage collection in any way, shape or form. Garbage collection and prompt resource clean-up are somewhat orthogonal.
Will Eddins comment:
Unless your class implements the IDisposable interface, and has a Dispose() function, you don’t use using.
The first snippet calls
Disposeat the end of the block – you can only do it with types which implementIDisposable, and it basically callsDisposein a finally block, so you can use it with types which need resources cleaning up, e.g.Note that this does not force garbage collection in any way, shape or form. Garbage collection and prompt resource clean-up are somewhat orthogonal.
Basically, you should use a
usingstatement for pretty much anything which implementsIDisposableand which your code block is going to take responsibility for (in terms of cleanup).