Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between 'using' and scoping?

Tags:

scope

c#

using

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.

like image 602
Kelsey Avatar asked Oct 30 '09 16:10

Kelsey


People also ask

What is the difference between scope and function?

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.

What is the use of scope?

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.

What is the difference between scope and context?

Scope pertains to the visibility of the variables, and context refers to the object within which a function is executed.

What is the difference between scoped and block scoped?

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.


1 Answers

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

like image 152
Jon Skeet Avatar answered Sep 21 '22 05:09

Jon Skeet