Skip to content

IDISP004 False positive when IDisposable struct is used as Enumerator #520

Open
@Houtamelo

Description

@Houtamelo

If you have a struct that implicitly acts as an Enumerator:

public struct EnumeratorStruct : IDisposable
{
    public int Current { get; }

    public bool MoveNext() => foo;

    public EnumeratorStruct GetEnumerator() => this;

    public void Dispose() => Console.WriteLine("Disposed");
}

If you use EnumeratorStruct as the supplier in a foreach statement, EnumeratorStruct.Dispose() is called but the analyzer still gives the IDISP004 warning.

All examples bellow are non-compliant despite being false-positives.

foreach (int element in new EnumeratorStruct())
{
    ...
}
public static EnumeratorStruct Enumerate(this Foo source) => new EnumeratorStruct(source);


Foo source = new Foo();
foreach (int element in source.Enumerate())
{
    ...
}
EnumeratorStruct enumerator = new EnumeratorStruct();
foreach (int element in enumerator)
{
    ...
}

Activity

Corniel

Corniel commented on Oct 18, 2024

@Corniel

I can confirm this issue.

Corniel

Corniel commented on Oct 18, 2024

@Corniel

I also created a PR to fix this.

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

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

      Participants

      @Corniel@Houtamelo

      Issue actions

        IDISP004 False positive when IDisposable struct is used as Enumerator · Issue #520 · DotNetAnalyzers/IDisposableAnalyzers