Tuesday, July 26, 2011

FxCop Rule CA2202 Do not dispose objects more than once

See the explanation in msdn:
http://msdn.microsoft.com/en-us/library/ms182334.aspx

Notice:

using( Stream stream = new FileStream(...))
{     
using(StreamWriter writer = new StreamWriter(stream))
  {         
  ....
  } 
}
this pattern the stream objects will be wrapped in the StreamWriter and will be disposed. In order that stream object will not be dispose more than once, we should write the following pattern:
Stream stream = null; 
try 
{     
 stream = new FileStream("file.txt", FileMode.OpenOrCreate);     
using(StreamWriter writer = new StreamWriter(stream))
  {        
      stream = null;         
      // Use the writer object...    
  }
 } 
finally 
{     
  if(stream != null)         
  stream.Dispose();
     // we dispose the stream object 
     //only it is not null 
}
We should remember this pattern.

No comments: