dotnet / dotnet/sdk

CA1001 doesn't get triggered for an auto-implemented property's backing field

Open
#54,089 0 comments 0 reactions 0 assignees View on GitHub
Area-Microsoft.CodeAnalysis.NetAnalyzers untriaged
Dominant language
C#
Stars
3.2k
Forks
1.3k
PR merge metrics
PR metrics pending

Description

**Version Used**:

- .NET SDK: `10.0.201`
- C# compiler: `5.3.0-2.26153.122 (4d3023de605a78ba3e59e50c657eed70f125c68a)`

**Steps to Reproduce**:

(Minimal reproducable repor: [yhslai/roslyn_ca1001](https://github.com/yhslai/roslyn_ca1001))

1. Create a class library project:

```bash
dotnet new classlib --framework net10.0
```

2. Enable CA1001 in `.editorconfig`:

```editorconfig
root = true

[*.cs]
dotnet_diagnostic.CA1001.severity = warning
```

3. Use the following source code:

```csharp
namespace RoslynCa1001Repro;

public class MyService1
{
public System.IO.MemoryStream DataStream = new();
}

public class MyService2
{
public System.IO.MemoryStream DataStream { get; } = new();
}
```

4. Build the project:

```bash
dotnet build
```

Minimal project file used:

```xml


net10.0
enable
enable
true
latest
RoslynCa1001Repro

```

**Diagnostic Id**:

`CA1001: Types that own disposable fields should be disposable`

Observed diagnostic:

```text
Class1.cs(3,14): warning CA1001: Type 'MyService1' owns disposable field(s) 'DataStream' but is not disposable
```

**Expected Behavior**:

Both `MyService1` and `MyService2` should produce CA1001, or the rule documentation should clarify why auto-property backing fields are excluded.

`MyService2` has a compiler-generated backing field for the get-only auto-property. That backing field stores a `System.IO.MemoryStream`, which implements `IDisposable`, and the containing type does not implement `IDisposable`. This appears to have the same ownership/disposal problem as the explicit field in `MyService1`.

**Actual Behavior**:

Only `MyService1` produces CA1001. `MyService2` produces no CA1001 warning.

Build output:

```text
Class1.cs(3,14): warning CA1001: Type 'MyService1' owns disposable field(s) 'DataStream' but is not disposable
Build succeeded.
1 Warning(s)
0 Error(s)
```

Contributor guide

No contributing guide indexed for this repository

Assessment

This issue has not been assessed yet.

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.