Skip to content

IDE0028 suggests uncompilable code for an enumerable type with a ctor featuring an optional string parameter #79156

@elgonzo

Description

@elgonzo

Version Used: dotnet-sdk-10.0.100-preview.5.25277.114-win-x64

Steps to Reproduce:

To start with a real-world example, the issue can be reproduced for example with System.CommandLine 2.0.0-beta6.25324.104 with a single code line RootCommand rcmd = new("root").

But for easier reproduction i made a simple repo code:

using System;
using System.Collections;


//
// This will trigger a false IDE0028 
//
Foo _ = new("foobar");


public class Foo(string s = "") : IEnumerable
{
    public void Add(Bar b) { _b = b; }

    IEnumerator IEnumerable.GetEnumerator()
        => throw new NotImplementedException();

    private Bar? _b;
}

public class Bar { }

Running dotnet format style --severity info --verify-no-changes will show:

Program.cs(8,9): info IDE0028: Collection initialization can be simplified

Allowing dotnet-format to apply style changes by running dotnet format style --severity info will replace the code line

Foo _ = new("foobar");

with

Foo _ = [.. "foobar"];

which is uncompilable code, resulting in the following errors when trying to compile it:

Program.cs(8,13): error CS1950: The best overloaded Add method 'Foo.Add(Bar)' for the collection initializer has some invalid arguments
Program.cs(8,10): error CS1503: Argument 1: cannot convert from 'char' to 'Bar'

Diagnostic Id:

IDE0028: Collection initialization can be simplified

Expected Behavior:

No IDE0028 on the line Foo _ = new("foobar");

Actual Behavior:

IDE0028 suggesting Foo _ = new("foobar"); to be changed to Foo _ = [.. "foobar"];.
Following the suggestion leads to uncompilable code.


Side note:
This issue is related (or a subset) of #73655, quite probably a duplicate. But the example code here featuring a constructor with an optional parameter might perhaps be an additional wrinkle to the issue, so i decided to file it as a separate issue instead of adding it as a comment to #73655.

Metadata

Metadata

Labels

Type

No type

Projects

No projects

Relationships

None yet

Development

No branches or pull requests

Issue actions