-3

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?

Madu
  • 4,849
  • 9
  • 44
  • 78

4 Answers4

1

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();
}
mlorbetske
  • 5,529
  • 2
  • 28
  • 40
1

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
Steve
  • 213,761
  • 22
  • 232
  • 286
0

By using 'using' you make sure that the object gets disposed of correctly.

The following question has some good answers on it:

Uses of "using" in C#

and also you could read the following on MSN:

MSDN C# Using

Community
  • 1
  • 1
Gaz Winter
  • 2,924
  • 2
  • 25
  • 47
0

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

Using Statement

Ted
  • 3,985
  • 1
  • 20
  • 33