dotnet / dotnet/roslyn

Roslyn fails to process `[NotNullIfNotNull]` annotation on extension properties

Open
#79,872 0 comments 1 reaction 1 assignee Claimed by @RikkiGibson View on GitHub
Area-Compilers Feature - Extension Everything
Dominant language
C#
Stars
20.7k
Forks
4.3k
PR merge metrics
PR metrics pending

Description

**Version Used**: 2e23a0df5bf8d49f6bf856287b0eb10de08f97d9

**Steps to Reproduce**:

Compile the following code
```csharp
using System.Diagnostics.CodeAnalysis;
#nullable enable

int? o1 = null;
o1.P1 = 1;
_ = o1.Value.ToString(); // CS8629 Nullable value type may be null

int? o2 = null;
E.set_P1(ref o2, 1);
_ = o2.Value.ToString(); // no warnings

public static class E
{
extension([NotNullIfNotNull("value")] ref int? o)
{
public int? P1 { get => o; set { o = value; } }
}
}
```

**Expected Behavior**:
No warnings.

**Actual Behavior**:
`CS8629 Nullable value type may be null` is reported after the `o1.P1` setter accessor invocation even though the annotation says the qualifier expression should not be null after it.

**Notes**:
Both `o1.P1 = 1` and `E.set_P1(ref o2, 1)` invoke the same member, but the former form of the call doesn't process the annotations on it.
Roslyn also enforces the contract from the annotation even though it ignores it on the call site. If annotations like this are not supposed to work perhaps they shouldn't be verified on the declaration site as well
```csharp
extension([NotNullIfNotNull("value")] ref int? o)
{
public int? P1 { get => o; set { o = null; } }
public int P2 { get => o ?? 0; set { o = null; } } // CS8824: Parameter 'o' must have a non-null value when exiting because parameter 'value' is non-null.
}
```

[jcouv update:] Relates to https://github.com/dotnet/roslyn/issues/78828 (nullability follow-ups for extensions)

Contributor guide

Open the contributing guide

Assessment

This issue has not been assessed yet.

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.