Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using the using statement in C# [duplicate]

Tags:

c#

using

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?

like image 740
FendFend Avatar asked Nov 26 '22 21:11

FendFend


2 Answers

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.

like image 166
cgreeno Avatar answered Dec 07 '22 05:12

cgreeno


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.

like image 31
mbillard Avatar answered Dec 07 '22 05:12

mbillard