Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Type inference fails for lambda expression returning collection expression #69488

Closed
cston opened this issue Aug 13, 2023 · 2 comments · Fixed by #71017
Closed

Type inference fails for lambda expression returning collection expression #69488

cston opened this issue Aug 13, 2023 · 2 comments · Fixed by #71017

Comments

@cston
Copy link
Member

cston commented Aug 13, 2023

Steps to Reproduce:

Compile:

using System;
using System.Collections.Generic;

class Program
{
    static void TupleResult<T>(Func<(T, T)> x)
    {
        Console.WriteLine(typeof(T).Name);
    }

    static void CollectionResult<T>(Func<T[]> x)
    {
        Console.WriteLine(typeof(T).Name);
    }

    static void Main()
    {
        TupleResult(() => (1, 2));
        CollectionResult(() => new[] { 1, 2 });
        CollectionResult(() => [1, 2]);
    }
}

Expected Behavior:
No errors, program reports "Int32 Int32 Int32".

Actual Behavior:
Error reported for collection expression case.

(20,9): error CS0411: The type arguments for method 'Program.CollectionResult<T>(Func<T[]>)'
    cannot be inferred from the usage. Try specifying the type arguments explicitly.

Relates to test plan #66418

@dotnet-issue-labeler dotnet-issue-labeler bot added Area-Compilers untriaged Issues and PRs which have not yet been triaged by a lead labels Aug 13, 2023
@cston cston self-assigned this Aug 13, 2023
@jcouv jcouv added this to the 17.8 milestone Aug 17, 2023
@jcouv jcouv removed the untriaged Issues and PRs which have not yet been triaged by a lead label Aug 17, 2023
@jcouv jcouv modified the milestones: 17.8, 17.9 Oct 11, 2023
@cston
Copy link
Member Author

cston commented Nov 29, 2023

The current behavior is by design since output type inference from a lambda expression requires the return value has a type. Since collection expressions do not have a natural type, type inference in the example fails as expected.

See 11.6.3.7 Output type inference:

  • If E is an anonymous function with inferred return type U and T is a delegate type or expression tree type with return type Tₓ, then a lower-bound inference is made from U to Tₓ.

See also collection expressions which builds on the output type inference rules.

@cston
Copy link
Member Author

cston commented Nov 29, 2023

Added test for current (expected) behavior in #71017.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

Successfully merging a pull request may close this issue.

2 participants