All rules
IDE0304Language rules (expression-level preferences)

Use collection expression for builder

Use collection expression for builder

Microsoft docs

Description

This rule flags places where a CreateBuilder() or similar method is called to create a builder type that adds elements and finally constructs a collection type that has the System.Runtime.CompilerServices.CollectionBuilderAttribute attribute (for example, by calling System.Collections.Immutable.ImmutableArray1.Builder.ToImmutable). Instead, a collection expression ([...]`) could be used to initialize the collection. This rule requires more recent versions of the immutable APIs (for example, System.Collections.Immutable), which opt in to the collection-expression pattern.

Example

// Code with violation.
var builder = ImmutableArray.CreateBuilder<int>();
builder.Add(1);
builder.AddRange(new int[] { 5, 6, 7 });
ImmutableArray<int> i = builder.ToImmutable();

// Fixed code.
ImmutableArray<int> i = [1, .. new int[] { 5, 6, 7 }];
Group results
0 yes 0 no
ConsensusNone (disabled)
Severity preference (yes voters)
Suggestion0
Warning0
Error0