Skip to content

Add analyzer rule for ArgumentException.ThrowIfContainsDuplicates #728

Description

@samtrion

Summary

NetEvolve.Arguments provides ArgumentException.ThrowIfContainsDuplicates(IEnumerable<T>, IEqualityComparer<T>?) to validate that a collection contains no duplicate elements. NetEvolve.Arguments.Analyser does not currently have a rule that detects the manual equivalent of this check.

Problem

The manual implementation of a duplicate check is a multi-statement algorithm rather than a single expression, e.g.:

var set = new HashSet<T>();
foreach (var item in arg)
{
    if (!set.Add(item))
    {
        throw new ArgumentException("The collection cannot contain duplicate elements.", nameof(arg));
    }
}

or the LINQ equivalent:

if (arg.Distinct().Count() != arg.Count())
{
    throw new ArgumentException(nameof(arg));
}

Because this spans a loop/multiple statements (not a single if (condition) throw ... expression) and has many equivalent formulations, it doesn't fit the single-expression pattern-matching approach used by the current rules and needs a dedicated design (e.g. matching on a HashSet<T>-based loop shape, or restricting scope to specific LINQ-based idioms).

Proposed solution

Design and implement a new rule (next available ID) that recognizes at least the most common LINQ-based shape (e.g. arg.Distinct().Count() != arg.Count() / .GroupBy(...).Any(g => g.Count() > 1)), with a code fix rewriting to ArgumentException.ThrowIfContainsDuplicates(arg). If reliable detection isn't feasible, document that decision and close as won't-fix.

References

Activity

  1. added theissue type on Sep 23, 2026
  2. added
    state:help wantedIndicate issues where additional help or contributions are needed from the community.
    on Sep 23, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    state:help wantedIndicate issues where additional help or contributions are needed from the community.

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions