CA2000 and CA2202 warnings have recently been the bane of my existence. What am I doing wrong here? I basically get a FileStream
using File.Open
and then pass it into a function that may return a new stream or may return the same stream. I then perform some more actions on my stream and then in my finally
block I dispose the stream I was using if it was different.
I get two CA warnings. 2000 for fileStream
in the using
block and 2202 for changedStream
in the finally
block. What gives?
using (Stream fileStream = File.Open(path, FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
{
Stream changedStream = null;
try
{
changedStream = someCondition ? fileStream : DoSomeActionThatMayReturnNewStream(fileStream);
DoSomeMoreStuffWithStream(changedStream);
}
finally
{
if (changedStream != null && changedStream != fileStream)
{
changedStream.Dispose();
}
}
}