7
votes

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!

2

2 Answers

15
votes

How could I call the Find method without specififying U?

You can't.

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>();
6
votes

How about writing

var people = repository.Find<Employee>();

It's saving the same amount of typing but in a different way.