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.
http://cbsa.com.br/post/c--por-que-usar-using.aspx I think you have a good explanation here.
– Marconi