When I compile code similar to
method BankAccount.Hascontent: Boolean;
begin
for each acc in Accounts do
begin
for each inst in acc.Instruments.Values do
begin
if inst.NetPosition<>0 then
exit true;
for each ord in inst.Orders.Values do
if ord.Qty>0 then
exit true;
End;
end;
exit false;
end;
and have Gendarme enabled I get 3 Gendarme warnings (I assume one for each foreach loop) for that method
Severity Code Description Project File Line Suppression State
Warning (High/Normal) This disposable local is not guaranteed to be disposed of before the method returns. Local of type ‘Enumerator’ is not disposed of (at least not locally). Nutcracker.CMS45.Utilities.AccountMonitor C:\wqa\Common\Nutcracker.CMS45.Utilities.AccountMonitor\BankAccount.pas 200
Which on the mono website reads as
DisposableFieldsShouldBeDisposedRule
The rule inspects all fields for disposable types and, if System.IDisposable is implemented, checks that the type’s Dispose method does indeed call Dispose on all disposable fields.
Bad example:
class DoesNotDisposeMember : IDisposable {
byte[] buffer;
IDisposable field;
public void Dispose ()
{
buffer = null;
// field is not disposed
}
}
Good example:
class DisposePattern : IDisposable {
byte[] buffer;
IDisposable field;
bool disposed;
public void Dispose ()
{
Dispose (true);
}
private void Dispose (bool disposing)
{
if (!disposed) {
if (disposing) {
field.Dispose ();
}
buffer = null;
disposed = true;
}
}
}
But we have no control on the enumerator to fix it.
Shouldn’t we at least assume that the compiler won’t introduce Gendarme correctness warnings.