Given the following extension method :
public static IOrderedEnumerable<TSource>
OrderBy<TSource, TKey>(
this IEnumerable<TSource> source,
Func<TSource, TKey> keySelector)
Here is how C# infers the types of the following Linq expression :
List<customer> customers = new List<Customer>
{
new Customer { FirstName = "Alice" },
new Customer { FirstName = "David" },
new Customer { FirstName = "Bob" },
};
customers.OrderBy(customer => customer.FirstName);
The two generic types of the extension method need to be inferred, namely TSource and TKey. First, TSource is inferred as type Customer from the fact that the extension method is is applied to an IEnumerable of Customers. Secondly, TKey is then inferred as type String from the fact that the provided lambda expression returns a String.
We can then express the fully typed extension method that will be used :
public static IOrderedEnumerable<Customer>
OrderBy<Customer, String>(
this IEnumerable<Customer> source,
Func<Customer, String> keySelector)
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment