0

How to replace this statement with try/finally block?

using(MemoryStream ms = new MemoryStream()){}

Is this the correct approach?

MemoryStream ms = new MemoryStream();
try
{
   //code
}
finally
{
   ms.Dispose();                
}
eXPerience
  • 326
  • 1
  • 2
  • 15

1 Answers1

3

It's rather like this:

MemoryStream ms = null;
try
{
   ms = new MemoryStream();

   //code
}
finally
{
   if (ms != null) ms.Dispose();                
}

The reason is that the mere instantiation may create disposable resources.

Ondrej Tucny
  • 26,707
  • 6
  • 66
  • 88