In C# 12 there's the "Collection initialization can be simplified" analyser IDE0028.
I've been wondering how the fixer decides when to fix or not fix initialisers such as new()
, new List<string>()
, new Collection<int>()
, Array.Empty<double>()
, new string[] { }
, etc. It's fix is to replace a qualifying initialiser with []
.
For example:
// Collection initialization can be simplified
public List<string> Foo1 { get; } = new List<string>();
public HashSet<string> Foo2 { get; } = new HashSet<string>();
public ICollection<string> Foo3 { get; } = new List<string>();
public Dictionary<int, string> Foo4 = new Dictionary<int, string>();
// Collection initialization can be simplified (may change semantics)
public IEnumerable<string> Bar1 { get; } = new List<string>();
public ICollection<string> Bar2 { get; } = new Collection<string>();
// no code fix offered
public IDictionary<int, string> Baz1 = new Dictionary<int, string>();
I usually choose a collection type that suits a specific purpose. So I don't want to blindly accept the analyser's recommendation without understanding what collection type the compiler will actually use when it sees []
.
So:
- How does the analyser/fixer decide when to suggest a fix, and what exactly does it mean by "may change semantics"
- What collection type does the compiler/runtime actually use when it encounters
[]
List
toICollection
, for example. – Hentrich