What is the use of using?

Asked

Viewed 3,644 times

23

My question is about 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?

  • http://cbsa.com.br/post/c--por-que-usar-using.aspx I think you have a good explanation here.

2 answers

23


The use of using allows classes that implement Idisposable are used in such a way as to ensure the execution of the method Dispose() at the end of its use, even if an exception is made.

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

Is 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 released if the method Dispose() is not called.

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

  • 2

    MemoryStream does not allocate Resources, only allocates one byte[]. FileStream would be a better example, because it allocates a SafeFileHandle, which in turn contains a IntPtr (Unmanaged).

  • 2

    By this I do not mean that it should not be called Dispose in a MemoryStream. IDisposable does not only serve to free Unmanaged Resources, serves to "clean" the object state - the definition of "clean" depends on the implementation, and can have several meanings. For this reason, it is good practice to call Dispose in all types that implement IDisposable.

8

The instruction using ensures that the Dispose be called, even when an exception occurs while you are calling methods on the object.

You can get the same result by placing the object in a Try block and then calling Dispose in a Finally block. Actually, that’s how the using statement is translated by the compiler.

{
    var memoryStream = new MemoryStream();

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

Browser other questions tagged

You are not signed in. Login or sign up in order to post.