Skip to content

Poor codegen for collection expression spread (IEnumerable<T> -> ImmutableArray<T>) #71296

Closed
@Sergio0694

Description

@Sergio0694

Related to #71195

Version Used: 4.9.0-ci (a8119d1)

Steps to Reproduce:

using System.Collections.Generic;
using System.Collections.Immutable;

static ImmutableArray<string> Test(IEnumerable<string> items)
{
    return [.. items];
}

sharplab

Expected Behavior:

return ImmutableArray.CreateRange(items);

OR

return items.ToImmutableArray();

Actual Behavior:

List<string> list = new List<string>();
IEnumerator<string> enumerator = items.GetEnumerator();
try
{
    while (enumerator.MoveNext())
    {
        string current = enumerator.Current;
        list.Add(current);
    }
}
finally
{
    if (enumerator != null)
    {
        enumerator.Dispose();
    }
}
return ImmutableCollectionsMarshal.AsImmutableArray(list.ToArray());

@RikkiGibson @CyrusNajmabadi not entirely sure whether the spec allows this, I think the problem is that the factory API is CreateRange, but [CollectionBuilder] over ImmutableArray<T> uses Create as the method name. Perhaps it would be possible to just hardcode these additional ImmutableArray<T> cases? Though it'd be nice to have a more general solution 🤔

Metadata

Metadata

Assignees

Labels

Area-CompilersCode Gen QualityRoom for improvement in the quality of the compiler's generated codeFeature - Collection Expressionshelp wantedThe issue is "up for grabs" - add a comment if you are interested in working on it

Type

No type

Projects

No projects

Relationships

None yet

Development

No branches or pull requests

Issue actions