dotnet / dotnet/roslyn

Unexpected nullable warning in object initializer member using extension Add method

Open
#81,102 4 comments 1 reaction 2 assignees Claimed by @RikkiGibson View on GitHub
Area-Compilers Feature - Extension Everything Feature - Nullable Reference Types
Dominant language
C#
Stars
20.7k
Forks
4.3k
PR merge metrics
PR metrics pending

Description

**Version Used**:

**Steps to Reproduce**: [.NET Lab](https://lab.razor.fyi/#fVHRihMxFGVhVzRPsl9wwIdpX2bFBxFrC6UUWVEQt0-KaDpzZwxk7pTkZrelzB_4Lz75Bz4K_onfIOlk266IeUhI7j3n5J6jfpwp9da1tdNNXvjz72ePOFirl5ZAHA8VvOEaVxsv1Izu3PJZay0VYlr2-Uticqb4T8dl0wSJlCOlCqu9RxJWWwUAXrSYAtetKfFGGx4Md899Ma7LOYeGXKR44cUZricwQo3HGB8-jvZ9nzAG0w1mieEuy44pobYJ3-HiAoFpvaJCqMSNdhynmF09e_rk8XNMXR0aYkFbQTYrQvaPv2QoNHMrWBKCpxJV67DSTjck5JBZ4yU7MLw2Xg5Qw8jma8lpLcTetHxbGhz3DTOUgSAtSlNV5IgL8hErXwh9cMYa2UQVR6kBUc_newO63qlOdbc5zFICq7C0psCxYrJqi5pkBB-3LtndKZUi61nma0k8hyEW6f-LCeL4fyeaBHeRT8tycOzqYoJrbQP5IcY9Op-W5TvNNQ1SYT_I-WmjDb-6R861zr9_cP_3t19ff1YPTz-frE_-AA)

```cs
#nullable enable
using System;
using System.Collections.Generic;
using System.Collections.Immutable;

class Program
{
static void Main()
{
IEnumerable items = [];
_ = new C()
{
Items = { items } // unexpected warning CS8620: Argument of type 'IEnumerable' cannot be used for parameter 'list' of type 'List' in 'Ext.extension(List)' due to differences in the nullability of reference types.
};
}
}

class C
{
public List Items { get; set; } = [];
}

static class Ext
{
extension(List list)
{
public void Add(IEnumerable values) => list.AddRange(values);
}
}
```

**Expected Behavior**: No warnings are reported

**Actual Behavior**: A nullable warning is reported for 'items'. Note that the parameter which is being referenced is also unexpected,

The bug is may be related to the adjustments which are made to extension calls in order to include the receiver argument. We would want to ensure that the scenario behaves similarly to an classic `public static void Add(this List list, IEnumerable values) => ...;` extension method.

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.