Skip to content

IDE0028 changes runtime semantics of read-only properties/members #83585

@TsengSR

Description

@TsengSR

Version Used:
From #error version: : '5.6.0-2.26180.1 (1068905)'. Language version: latest (14.0).

Steps to Reproduce:

  1. public class Example
    {
        private readonly IEnumerable<Foo> bar = new List<Fo>();
    
        public IEnumerable<Foo> Foo { get; } = new List<Fo>();
    }
  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<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.

Metadata

Metadata

Assignees

No one assigned

    Type

    No type
    No fields configured for issues without a type.

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions