Search code examples
c#genericstypesinference

Type inference in lambdas


I have this functionality:

 public class Repository : IRepository
    {
        public List<TEntity> GetOrdered<TEntity, TSortKey>(Func<TEntity, TSortKey> orderBy, int take, params string[] includePaths) where TEntity : AbstractEntity
        {
            var query = (from ent in this.Context.Set<TEntity>() select ent).IncludePaths(includePaths);

            return query.OrderBy(orderBy).Take(take).ToList();
        }
    }    

To invoke it:

List<Project> p = repository.GetOrdered<Project, string>(x => x.Name, 10);

I want to eliminate the need to give it the second generic parameter when invoking, it's a deal breaker from an API perspective.

How to do it?


Solution

  • Either the compiler can infer all type parameters, or you have to specify them all. But you may explicitly specify the argument type of the lambda expression, such as:

    List<Project> p = repository.GetOrdered((Project x) => x.Name, 10);