Skip to content

Extend the "Use collection expression" suggestion to scenarios requiring the spread operator #75870

@obonn1

Description

@obonn1

Summary

Expand the Roslyn analyzers to suggest using [.. collection] syntax where applicable. This is a more concise and expressive way to initialize collection from elements in existing collections.

Background and Motivation

The IDE currently suggests collection initialization when a spread operator wouldn't be required. The motivation for this feature is the same as the existing suggestions, informing developers of the existence of a more readable syntax. Notably, ReSharper already suggests using collection expressions in these situations. Adding this feature directly to Roslyn would ensure consistency and improve native support for modern C# practices.

Proposed Feature

Before:

List<int> GetNumbers()
{
    return new List<int>(Enumerable.Range(1, 10));
}

After:

List<int> GetNumbers()
{
    return [.. Enumerable.Range(1, 10)];
}

Before:

ImmutableArray<string> GetFormattedNumbers(ImmutableArray<int> numbers)
{
    return numbers.Select(n => $"Number: {n}").ToImmutableArray();
}

After:

ImmutableArray<string> GetFormattedNumbers(ImmutableArray<int> numbers)
{
    return [.. numbers.Select(n => $"Number: {n}")];
}

Before:

ImmutableArray<string> GetFormattedRange()
{
    return ImmutableArray.CreateRange(Enumerable.Range(1, 10).Select(n => $"Item {n}"));
}

After:

ImmutableArray<string> GetFormattedRange()
{
    return [.. Enumerable.Range(1, 10).Select(n => $"Item {n}")];
}

Metadata

Metadata

Assignees

No one assigned

    Labels

    Area-IDEFeature Requesthelp wantedThe issue is "up for grabs" - add a comment if you are interested in working on it

    Type

    No type

    Projects

    Status

    Completed

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions