Skip to content

CA2213 false positive when using primary constructor with fields #7803

@DemoBytom

Description

@DemoBytom

If a class implements IDisposable and contains a constructor-set IDisposable field that isn't owned by that class, a false positive CA2213 is reported if primary constructor with fields is used.
Diagnostic is not reported for regular constructor, or a primary constructor without fields

Reproduction:

public class Foo : IDisposable
{
    private readonly Bar _bar;
    public Bar ReturnBar() => _bar;
    public Foo(Bar bar)
    {
        _bar = bar;
    }

    public void Dispose() { }
}

public class Foo2(Bar bar) : IDisposable
{
    private readonly Bar _bar = bar; // CA2213: 'Foo2' contains field '_bar' that is of IDisposable type 'Bar', but it is never disposed. Change the Dispose method on 'Foo2' to call Close or Dispose on this field.
    public Bar ReturnBar() => _bar;
    public void Dispose() { }
}

public class Foo3(Bar bar) : IDisposable
{
    public Bar ReturnBar() => bar;
    public void Dispose() { }
}

public sealed class Bar : IDisposable
{
    public void Dispose() { }
}
Image

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type
    No fields configured for issues without a type.

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions