All rules
IDE0303Language rules (expression-level preferences)
Use collection expression for Create
Use collection expression for Create
Microsoft docsDescription
This rule flags places where a Create() method or a similar method that's designated as the collection construction method (using the System.Runtime.CompilerServices.CollectionBuilderAttribute attribute) is used to initialize a collection and offers to replace it with a collection expression ([...]).
Create() methods are common for the immutable collections, for example, ImmutableArray.Create(1, 2, 3). 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 violations.
ImmutableArray<int> i = ImmutableArray.Create(1, 2, 3);
IEnumerable<int> j = ImmutableArray.Create(1, 2, 3);
// Fixed code.
ImmutableArray<int> i = [1, 2, 3];
IEnumerable<int> j = [1, 2, 3];
public class Program
{
public static void Main()
{
// IDE0303 violation.
MyCollection<int> c = MyCollection.Create(1, 2, 3);
// IDE0303 fixed code.
MyCollection<int> c = [1, 2, 3];
}
}
static partial class MyCollection
{
public static MyCollection<T> Create<T>(System.ReadOnlySpan<T> values) => default;
public static MyCollection<T> Create<T>(T t1, T t2, T t3) => default;
}
[CollectionBuilder(typeof(MyCollection), "Create")]
class MyCollection<T> : IEnumerable<T>
{
public IEnumerator<T> GetEnumerator() => default;
IEnumerator IEnumerable.GetEnumerator() => default;
}Your vote
Group results
0 yes 0 no
ConsensusNone (disabled)
Severity preference (yes voters)
Suggestion0
Warning0
Error0