This rule flags places where a collection expression could be used to initialize an array. For example, this rule offers to simplify code like new C[] { ... }, new[] { ... }, and C[] c = { ... } into the collection expression form ([...]).
Options
Options specify the behavior that you want the rule to enforce. For information about configuring options, see Option format.
dotnet_style_prefer_collection_expression
Property
Value
Description
Option name
dotnet_style_prefer_collection_expression
Option values
true | when_types_exactly_match
Prefer to use collection expressions only when types match exactly, for example, int[] i = new int[] { 1, 2, 3 };.
when_types_loosely_match (.NET 9 and later versions)*
Prefer to use collection expressions even when types match loosely, for example, IEnumerable<int> i = new int[] { 1, 2, 3 };. The targeted type must match the type on the right-hand side or be one of the following types: IEnumerable<T>, ICollection<T>, IList<T>, IReadOnlyCollection<T>, IReadOnlyList<T>.
false | never
Disables the rule.
Default option value
true in .NET 8 when_types_loosely_match in .NET 9 and later versions
*The code fix when this option is used might change the semantics of your code. For example, if you had IEnumerable<int> x = new int[] { 1, 2, 3 };, then in the original code, an array is produced. But in the new code (IEnumerable<int> x = [1, 2, 3];), an internal compiler-synthesized type is produced instead. You can observe this difference if you use an is check or a cast.
Bạn có thể tìm thấy nguồn cho nội dung này trên GitHub, nơi bạn cũng có thể tạo và xem lại các vấn đề và yêu cầu kéo. Để biết thêm thông tin, hãy xem hướng dẫn dành cho người đóng góp của chúng tôi.
Ý kiến phản hồi về .NET
.NET là một dự án nguồn mở. Chọn liên kết để cung cấp ý kiến phản hồi:
Tham gia chuỗi buổi gặp gỡ để xây dựng các giải pháp AI có thể mở rộng dựa trên các trường hợp sử dụng trong thế giới thực với các nhà phát triển và chuyên gia đồng nghiệp.