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!
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>();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With