tags:

views:

1198

answers:

7

Possible Duplicate:
What is the C# Using block and why should I use it?

I have seen the using statement used in the middle of a codeblock what is the reason for this?

+33  A: 

The using syntax can(should) be used as a way of defining a scope for anything that implements IDisposable. The using statement ensures that Dispose is called if an exception occurs.

    //the compiler will create a local variable 
    //which will go out of scope outside this context 
    using (FileStream fs = new FileStream(file, FileMode.Open))
    {
         //do stuff
    }

Alternatively you could just use:

    FileStream fs;
    try{
       fs = new FileStream();
       //do Stuff
    }
    finally{
        if(fs!=null)
           fs.Dispose();
    }

Extra reading from MSDN

C#, through the .NET Framework common language runtime (CLR), automatically releases the memory used to store objects that are no longer required. The release of memory is non-deterministic; memory is released whenever the CLR decides to perform garbage collection. However, it is usually best to release limited resources such as file handles and network connections as quickly as possible.

The using statement allows the programmer to specify when objects that use resources should release them. The object provided to the using statement must implement the IDisposable interface. This interface provides the Dispose method, which should release the object's resources.

cgreeno
+1 - nice answer - it is important to note that the compiler actually replaces the using statement with try/finally.
Andrew Hare
+2  A: 

The using statement ensures an object is properly disposed once it is nolonger required. It basically saves you writing obj.Dispose(); and gives a visual guide as to the scope and usage of an variable.

See the MSDN page for more info

Greg B
+3  A: 

It is often used when opening a connection to a stream or a database.

It behaves like a try { ... } finally { ... } block. After the using block, the IDisposable object that was instantiated in the parenthesis will be closed properly.

using (Stream stream = new Stream(...))
{


}

With this example, the stream is closed properly after the block.

GoodEnough
+3  A: 

using is try finally syntaxical suger for anything that has an IDisposable.. like a sqlconnection. Its use it make sure something is disposed after its out of the using(){} scope.

using(SqlConnection conn = new SqlConnection(connString))
{
  //use connection
}

//shorter than

SqlConnection conn = new SqlConnection(connString)
try
{
  //use connection 
}
finally
{
    conn.Dispose();
}
Hath
+2  A: 

This form of using has to do with freeing resources. It can only be used in combination with class that implement the IDisposable interface.

example:

using(SqlConnection conn = new SqlConnection(someConnectionString))
{
     //Do some database stuff here
}

at the end of the using block conn.Dispose is called, even if an exception was thrown inside the block. In the case of a SwqlConnection object means that the connection is always closed.

A drawback of this construction is that there is now way of knowing what happend.

Hope this helps answer your question?

norbertB
+2  A: 

Whenever your code creates an object that implements IDisposable, your code should do the creation inside a using block, as seen above.

There is one exception to this rule. An error in the design of WCF proxy classes prevents using statements from being useful for proxy classes. Briefly, the Dispose method on a proxy class may throw an exception. The WCF team saw no reason not to permit this.

Unfortunately, not seeing a reason doesn't mean that there is no reason:

try
{
    using (var svc = new ServiceReference.ServiceName())
    {
        throw new Exception("Testing");
    }
}
catch (Exception ex)
{
    // What exception is caught here?
}

If the implicit Dispose call throws an exception, then the catch block will catch that exception instead of the one thrown within the using block.

John Saunders