Version Used:
From #error version: : '5.6.0-2.26180.1 (1068905)'. Language version: latest (14.0).
Steps to Reproduce:
-
public class Example
{
private readonly IEnumerable<Foo> bar = new List<Fo>();
public IEnumerable<Foo> Foo { get; } = new List<Fo>();
}
- Suggestion will appear to change it to
[] on both, the field and the property.
- When using specific libraries which inspect the concrete type, they fail, because the collection is read-only.
AutoMapper is one such example, but others too like EF Core where a collection can be declared as IEnumerable<T> , but initialized with a mutable collection for populating.
This allows both libraries to populate the underlying list during mapping (AutoMapper) or materialization (EF Core).
In EF Core a popular pattern is
public class Foo
{
public IEnumerable<Bar> Bar { get; } = new List<Bar>();
}
to ensure read-only semantics but still allow EF Core to populate it
Ef Core: Collection types
Diagnostic Id:
IDE0028 : Collection initialization can be simplified
Expected Behavior:
Not receive a suggestion. If the collection is NOT assigable (i.e. being read-only property with only a getter and no setter or a readonly member), do not show the suggestion.
Even going further I'd suggest adding a new Diagnostic for obsolete/assigned but never changing field when [] or immutable empty collection is assigend to a readonly field/property.
Actual Behavior:
Suggestion is shown and when applied, breaks existing behavior depending on the collection being mutable.
Version Used:
From #error version: : '5.6.0-2.26180.1 (1068905)'. Language version: latest (14.0).
Steps to Reproduce:
[]on both, the field and the property.AutoMapper is one such example, but others too like EF Core where a collection can be declared as
IEnumerable<T>, but initialized with a mutable collection for populating.This allows both libraries to populate the underlying list during mapping (AutoMapper) or materialization (EF Core).
In EF Core a popular pattern is
to ensure read-only semantics but still allow EF Core to populate it
Ef Core: Collection types
Diagnostic Id:
IDE0028 : Collection initialization can be simplified
Expected Behavior:
Not receive a suggestion. If the collection is NOT assigable (i.e. being read-only property with only a getter and no setter or a readonly member), do not show the suggestion.
Even going further I'd suggest adding a new Diagnostic for obsolete/assigned but never changing field when
[]or immutable empty collection is assigend to a readonly field/property.Actual Behavior:
Suggestion is shown and when applied, breaks existing behavior depending on the collection being mutable.