Improve codegen for certain collection types.
- Dominant language
- C#
- Stars
- 20.7k
- Forks
- 4.3k
- PR merge metrics
- PR metrics pending
Description
**Version Used**:
Dotnet 9.0.
**Steps to Reproduce**:
1. Compile:
```c#
using System.Collections.Generic;
string[] strings = ["hello", "world"];
HashSet myset = new(strings);
```
A minimal repro, with source-code provided, is ideal. Most compiler/language issues can be distilled into a snippet that can be pasted into [sharplab](https://sharplab.io/).
**Diagnostic Id**:
[IDE0028](https://learn.microsoft.com/dotnet/fundamentals/code-analysis/style-rules/ide0028): Collection initialization can be simplified
**Expected Behavior**:
No diagnostic.
**Actual Behavior**:
IDE0028 is raised and suggests changing syntax to `[.. strings]`. This syntax is effectively:
```C#
HashSet hashSet = new HashSet();
for (int i = 0; i < strings.Length; i++)
{
hashSet.Add(strings[i]);
}
```
This is less efficient since it will initialize the collection with default capacity and then grow / copy as Adds are made. Collection constructors should be preferred in most cases since they can more-efficiently initialize the internal collection than calling Add N times.
Contributor guide
Assessment
This issue has not been assessed yet.