Search code examples
linqc#-3.0

Why cannot type arguments be inferred from this simple code?


Using .NET 3.5, but the Select call gives the error. Shouldn't the compiler be clever enough to infer this? If not, why not?

public IEnumerable<Customer> TableToCustomers(Table table)
{
    return table.Rows.Select(RowToCustomer);
}

private Customer RowToCustomer(TableRow row)
{
    return new Customer { ... };
}

Solution

  • The Rows property is defined as TableRowCollection Rows {get;}

    public sealed class TableRowCollection : IList, ICollection, IEnumerable
    

    It is not IEnumerable<TableRow>, so it is just IEnumerable, therefore it cannot infer the type as being TableRow.

    You can do this instead:

    public IEnumerable<Customer> TableToCustomers(Table table)
    {
        return table.Rows.Cast<TableRow>().Select(RowToCustomer);
    }