dotnet/roslyn

Improve error message for explicit cast of collection literal to non-generic type

Open

#68.862 aperta il 3 lug 2023

Vedi su GitHub
 (2 commenti) (1 reazione) (0 assegnatari)C# (4257 fork)batch import
Area-CompilersConcept-Diagnostic ClarityFeature - Collection Expressionshelp wanted

Metriche repository

Star
 (20.414 star)
Metriche merge PR
 (Merge medio 6g 17h) (256 PR mergiate in 30 g)

Descrizione

Compile:

using System;
using System.Collections;
using System.Collections.Generic;

class C : IEnumerable<int>
{
    public void Add(int i) { }
    public IEnumerator<int> GetEnumerator() => null;
    IEnumerator IEnumerable.GetEnumerator() => GetEnumerator();
}

class Program
{
    static void Main()
    {
        var c = (C)[1];
    }
}

Actual Behavior:

(16,18): error CS0119: 'C' is a type, which is not valid in the given context

Expected Behavior: Diagnostic above, with suggestion to parenthesize the collection literal if a cast is intended.

See https://github.com/dotnet/roslyn/pull/68793#discussion_r1245560632

Relates to test plan https://github.com/dotnet/roslyn/issues/66418

Guida contributor