IDE0028 changes runtime semantics of read-only properties/members
- Dominant language
- C#
- Stars
- 20.7k
- Forks
- 4.3k
- PR merge metrics
- PR metrics pending
Description
**Version Used**:
From #error version: : '5.6.0-2.26180.1 (106890564f33f6642b625e99bed73b3e9a15244e)'. Language version: latest (14.0).
**Steps to Reproduce**:
1.
```csharp
public class Example
{
private readonly IEnumerable bar = new List();
public IEnumerable Foo { get; } = new List();
}
```
2. Suggestion will appear to change it to `[]` on both, the field and the property.
3. 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` , 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
```csharp
public class Foo
{
public IEnumerable Bar { get; } = new List();
}
```
to ensure read-only semantics but still allow EF Core to populate it
[Ef Core: Collection types](https://learn.microsoft.com/en-us/ef/core/modeling/relationships/navigations#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.
Contributor guide
Research direction
No source file or test is named. Start by reproducing the IDE0028 suggestion with the readonly field and getter-only property examples, then trace the IDE0028 analyzer and its existing tests. Done means the simplification is no longer suggested for non-assignable collections while applicable cases retain their current behavior.
Written by the indexing model from the issue text.
Assessment
- Tech stack
- csharp
- Domain
- tooling
- Issue type
- Bug
- Difficulty
- 3/5
- Estimated time
- 1-2 days
- Activity status
- Quiet
- Clarity
- Mostly clear
- Newbie friendliness
- 58/100