Skip to content

Add analyzer rule for ArgumentException.ThrowIfNullOrEmpty on collections #727

Description

@samtrion

Summary

NetEvolve.Arguments.Analyser currently ships a rule (NEA0002) that recognizes string.IsNullOrEmpty(arg)-then-throw and rewrites it to ArgumentException.ThrowIfNullOrEmpty(arg). NetEvolve.Arguments also provides overloads of ArgumentException.ThrowIfNullOrEmpty for IEnumerable<T>, ICollection<T>, IReadOnlyCollection<T>, and T[], but no analyzer rule currently detects the equivalent manual check for collections.

Problem

Unlike the string case, a manual "collection is null or empty" check has no single canonical shape. Examples seen in the wild:

if (arg is null || !arg.Any())
    throw new ArgumentException(nameof(arg));

if (arg is null || arg.Count == 0)
    throw new ArgumentException(nameof(arg));

if (arg is null || arg.Length == 0)
    throw new ArgumentException(nameof(arg));

Reliably recognizing all equivalent forms (LINQ Any(), Count/Length property, Count() extension method, differing null-check styles, differing operand order) without producing false positives or false negatives needs more design work than the other rules, which is why it was deliberately left out of the initial rule set.

Proposed solution

Design and implement a new rule (next available ID, e.g. NEA0010) that recognizes at least the most common shapes above for IEnumerable<T>/ICollection<T>/IReadOnlyCollection<T>/T[] arguments, with a code fix rewriting to ArgumentException.ThrowIfNullOrEmpty(arg).

References

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions