Skip to content

Extension methods aren't being factored into collection expressions #9688

@stephentoub

Description

@stephentoub

Version Used:
https://github.com/dotnet/roslyn/commits/e3cf188c71ec62089866f0e99bd535cd47878659

Steps to Reproduce:

U u = new();

List<T> list1 = [];
list1.Add(u); // works fine

List<T> list2 = [u]; // fails to compile with "Cannot implicitly convert type 'U' to 'T'"

class T;
class U;

class Adapter(U u) : T;

static class Extensions
{
    public static void Add(this List<T> list, U u) => list.Add(new Adapter(u));
}

Diagnostic Id:
CS0029

Expected Behavior:
Compiles

Actual Behavior:
Fails to compile

The spec seems to suggest this should work?
https://github.com/dotnet/csharplang/blob/main/proposals/csharp-12.0/collection-expressions.md
e.g. "If the collection expression has any elements, the type has an instance or extension method Add where: The method can be invoked with a single value argument"

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    Status

    Language/design

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions