dotnet / dotnet/roslyn

Nullability mismatch is not repoted for collection expressions' implicit `.Add` call receivers

Open
#79,803 1 comment 0 reactions 1 assignee Claimed by @RikkiGibson View on GitHub
Area-Compilers Bug Feature - Collection Expressions Feature - Nullable Reference Types
Dominant language
C#
Stars
20.7k
Forks
4.3k
PR merge metrics
PR metrics pending

Description

**Version Used**: 2e23a0df5bf8d49f6bf856287b0eb10de08f97d9

**Steps to Reproduce**:

Compile and run the following code:
```csharp
using System;
using System.Collections;
using System.Collections.Generic;
#nullable enable

string? obj = null;
C c = [obj];
foreach (string o in c)
{
Console.WriteLine(o.Length);
}

// both lines below would report CS8620:
// c.Add(obj);
// c = new() { obj };

class C : IEnumerable
{
internal List _list = new();

IEnumerator IEnumerable.GetEnumerator() => _list.GetEnumerator();
public IEnumerator GetEnumerator() => _list.GetEnumerator();
}

static class Ext
{
public static void Add(this C c, T t) { c._list.Add(t); }
}
```

**Diagnostic Id**:

`CS8620 Argument type cannot be used for a parameter because of differences in the nullability of reference types`

**Expected Behavior**:
CS8620 warning reported for `[obj]` collection expression.
Note that if collection expression is replaced with either collection initializer or explicit `.Add` call the warning is correctly reported

**Actual Behavior**:
No warnings at all. The code crashes at runtime with a `NullReferenceException`

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.