c# – What is the use of using?

Question:

My question is regarding the difference between:

//Bloco 1
using (var memoryStream = new MemoryStream())
{
    //código
}

//Bloco 2
{
    var memoryStream = new MemoryStream();
    //código
}

Deep down they seem to be the same thing. Is there any difference?

Answer:

Using using allows classes that implement IDisposable to be used in such a way as to guarantee the execution of the Dispose() method at the end of its use, even if it throws an exception.

using (var memoryStream = new MemoryStream())
{
    //código
}

It's equivalent to:

{
    var memoryStream = new MemoryStream();
    try
    {
        //código    
    }
    finally
    {
        if (memoryStream != null)
        {
            memoryStream.Dispose();
        }
    }
}

Classes that implement IDisposable usually allocate unmanaged resources , or others, which will not be freed if the Dispose() method is not called.

Whenever a class implements the method IDisposable Dispose() should be called explicitly or implicitly this using block using.

Scroll to Top