Skip to content

BSL173 — Deleting an item when iterating through collection using the operator "For each ... In ... Do"

Summary

Deleting an item when iterating through collection using the operator "For each ... In ... Do"

Identifiers

Field Value
Rule code BSL173
Compatible alias DeletingCollectionItem
Severity ERROR
Enabled by default Yes
Implemented Yes
Tags correctness, loop

Behavior

  • The public identifier BSL173 and alias DeletingCollectionItem are stable.
  • The rule reports the cases documented on this page.
  • Suppressions and project configuration are applied before publication.
  • The rule requires neither an external analyzer nor network access.

Configuration and suppression

BSL### is the primary stable identifier. The compatible alias is accepted in select, ignore, and compatible block suppression comments.

[tool.onec-hbk-bsl]
select = ["BSL173"]
ignore = ["DeletingCollectionItem"]

All three suppression families support both a current line and a range. When an opening comment follows code, it affects only that line. Use any one form:

  • noqa:
Value = "example";  // noqa: BSL173
  • bsl-disable:
Value = "example";  // bsl-disable: BSL173
  • compatible BSLLS form:
Value = "example";  // BSLLS:DeletingCollectionItem-off

When the same opening comment is on a line by itself, it starts a range. Close it with the matching marker from the same family:

// noqa: BSL173
// code without this diagnostic
// noqa-enable: BSL173

// bsl-disable: BSL173
// code without this diagnostic
// bsl-enable: BSL173

// BSLLS:DeletingCollectionItem-off
// code without this diagnostic
// BSLLS:DeletingCollectionItem-on

To disable the rule until the end of the file, omit the closing noqa-enable, bsl-enable, or BSLLS:…-on marker.

Opening and closing markers must belong to the same family.

Description

Don't delete elements of collection when iterating through collection using the operator For each ... In ... Do. Because it change index of next element.

Example:

For each Element In Collection Do
   Collection.Delete(Element)
EndDo;

Alternatively, remove elements from the end:

IndexOf = Numbers.UBound();
While IndexOf >= 0 Do
    If Numbers[IndexOf] < 10 Then
        Numbers.Delete(IndexOf);
    EndIf;
    IndexOf = IndexOf – 1;
EndDo;

Sources