I have an object that uses some underlying native resources, and has a pointer to the next instance, which I iterate through similar to:
MyObject begin = null;
try
{
begin = GetFirst();
while (begin != null)
{
MyObject next = begin.Next();
// do something with begin
begin.Dispose();
begin = next;
}
}
finally
{
if (begin != null)
{
begin.Dispose();
}
}
I get the code analysis problem:
CA2202: Microsoft.Usage: Object 'begin' can be disposed more than once in method 'x()'. To avoid generating a System.ObjectDisposedException you should not call Dispose more than one time on an object.
Any idea how I can get rid of this error without suppressing it?
It certainly seems to me that your last block of code is unnecessary. If
begin != null
, then yourwhile
loop should have continued, no?UPDATE: It looks like you're trying to ensure the last obtained value for
begin
is disposed in case an exception is thrown. Try this:Note that in the above suggestion, it could actually still happen that you end up with an undisposed object: the last value assigned to
next
, before the end of theusing
block. This scenario wasn't covered in your original question, so I haven't addressed it in the above suggestion. It's something to consider, though, if that's a potential problem.