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 scope determines the accessibility of variables and other resources in the code, like functions and objects. JavaScript function scopes can have two different types, the locale and the global scope. Local variables are declared within a function and can only be accessed within the function.
Scope refers to the combined objectives and requirements needed to complete a project. The term is often used in project management as well as in consulting. Properly defining the scope of a project allows managers to estimate costs and the time required to finish the project.
Scope pertains to the visibility of the variables, and context refers to the object within which a function is executed.
Function scoped variables: A function scoped variable means that the variable defined within a function will not accessible from outside the function. Block scoped variables: A block scoped variable means that the variable defined within a block will not be accessible from outside the block.
The first snippet calls Dispose
at the end of the block - you can only do it with types which implement IDisposable
, and it basically calls Dispose
in a finally block, so you can use it with types which need resources cleaning up, e.g.
using (TextReader reader = File.OpenText("test.txt"))
{
// Use reader to read the file
}
// reader will be disposed, so file handle released
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 using
statement for pretty much anything which implements IDisposable
and which your code block is going to take responsibility for (in terms of cleanup).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With