i am unable to understand the using
syntax of c#. i have seen many code snippets using
code like.
using (StreamReader rdr = File.OpenText("file.txt"))
{
//do stuff
}
What is the meaning of that syntax is it some kind of loop?
i am unable to understand the using
syntax of c#. i have seen many code snippets using
code like.
using (StreamReader rdr = File.OpenText("file.txt"))
{
//do stuff
}
What is the meaning of that syntax is it some kind of loop?
The using
syntax is a wrapper for making sure resources are disposed (operates on things that implement IDisposable
), that you are using a particular resource for the scope of the block that follows it.
A using
statement is just syntactic sugar for this:
StreamReader rdr = File.OpenText("file.txt");
try
{
//do stuff
}
finally
{
rdr.Dispose();
}
The using statement is a very useful way to handle objects that need to be disposed and or closed
It substitutes code like this
StreamReader sr = new StreamReader(....)
try
{
.... use the StreamReader
}
finally
{
sr.Dispose();
}
as you can see, an object declared inside the using intial line is always passed to the finally block and its dispose method is called ALSO in case of exceptions
The using statement should not be confused with the using directive that is used
to allow the use of types in a namespace so that you do not have to qualify the use of a type in that namespace, and to create an alias for a namespace or a type. This is called a using alias directive.
using System.IO; // Allows to type StreamReader instead of System.IO.StreamReader
using Project = PC.MyCompany.Project; // Allows to type just Project.MyClass
By using 'using' you make sure that the object gets disposed of correctly.
The following question has some good answers on it:
and also you could read the following on MSN:
No, it is not a loop. It is a statement which denotes a new code-block inside another code-block. The good think about this is that you don't have to dispose of the objects that are initialized in the using
statement but that means that they have to be IDisposable
in order to be used like that. The newer versions of the .NET framework, handle the disposed objects rather nicely and that minimizes the memory footprint of the application. It also makes long procedures better structured and more readable (in my opinion).