Reputation: 23094
Given the following generic interface and implementing class:
public interface IRepository<T> {
// U has to be of type T of a subtype of T
IQueryable<U> Find<U>() where U : T;
}
public class PersonRepository : IRepository<Employee> {
}
How could I call the Find method without specififying U?
var repository = new EmployeeRepository();
// Can't be done
IQueryable<Employee> people = repository.Find();
// Has to be, but isn't Employee a given in this context?
IQueryable<Employee> people = repository.Find<Employee>();
// Here I'm being specific
IQueryable<Manager> managers = repository.Find<Manager>();
In other words, what can be done to get type inference?
Thanks!
Upvotes: 7
Views: 4405
Reputation: 62970
How could I call the Find method without specififying U?
Unfortunately C#'s generic method overload resolution doesn't match based on return values.
See Eric Lippert's blog post about it: C# 3.0 Return Type Inference Does Not Work On Method Groups
But one easy way to write this is using var
keyword.
var employees = repository.Find<Employee>();
Upvotes: 15
Reputation: 29956
How about writing
var people = repository.Find<Employee>();
It's saving the same amount of typing but in a different way.
Upvotes: 6