dotnet/roslyn

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

Open

#68,862 opened on Jul 3, 2023

View on GitHub
 (2 comments) (1 reaction) (0 assignees)C# (4,257 forks)batch import
Area-CompilersConcept-Diagnostic ClarityFeature - Collection Expressionshelp wanted

Repository metrics

Stars
 (20,414 stars)
PR merge metrics
 (Avg merge 6d 17h) (256 merged PRs in 30d)

Description

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

Contributor guide