Skip to content

Proposal: Infer generic type based on target #5429

@HaloFour

Description

@HaloFour

Problem

When calling generic methods where the generic type parameter is only used as the return value of the method there is currently no inference which leads to repetition.

DataTable table = ...;
var people = table.Rows
    .Select(row => new Person {
        Id = row.Field<int>("id"),
        Name = row.Field<string>("name"),
        Birthdate = row.Field<DateTime>("dob")
    })
    .ToList();

Proposal

It would be convenient if in the specific case of the generic type parameter being the return type if the compiler could infer the generic type argument based on the destination of the result. This would only be permitted if the method is called in an unambiguous fashion. The return value must be assigned to a destination with an explicit type and there can be no other non-generic methods with the same name and parameters.

int id = row.Field("id"); // legal, generic type argument inferred to be int
var id = row.Field("id"); // not legal, circular inference
row.Field("id"); // not legal, no assignment to a type

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions