Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# type inference of a generic method type parameter where the method has no arguments

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!

like image 876
Michiel van Oosterhout Avatar asked Jan 28 '09 12:01

Michiel van Oosterhout


1 Answers

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>();
like image 62
Pop Catalin Avatar answered Sep 29 '22 12:09

Pop Catalin